Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning python dictionary literals: are the semantics guaranteed? [duplicate]

Simple question:

Python 2.6.6 (r266:84292, Aug 9 2016, 06:11:56)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {'foo':1,'foo':2}
>>> print d
{'foo': 2}
>>> d = {'foo':2,'foo':1}
>>> print d
{'foo': 1}

So it seems that if I assign a dictionary literal with a duplicate key to a variable it is the second key/pair that is used, at least for this particular python version.

Is this behaviour guaranteed?

like image 462
David Davies Avatar asked Nov 03 '17 09:11

David Davies


1 Answers

From the Dictionary displays documentation:

If a comma-separated sequence of key/datum pairs is given, they are evaluated from left to right to define the entries of the dictionary: each key object is used as a key into the dictionary to store the corresponding datum. This means that you can specify the same key multiple times in the key/datum list, and the final dictionary’s value for that key will be the last one given.

(Bold emphasis mine).

So yes, that is guaranteed. All Python implementations must adhere to this, deviation from the above specification would be a bug.

Older Python version documentation have not always included that last sentence, but the order of evaluation has always been explicit.

like image 166
Martijn Pieters Avatar answered Sep 28 '22 05:09

Martijn Pieters