7

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?

1 Answers1

8

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • The text for Python 2.6 (which the OP uses) is a bit different: https://docs.python.org/2.6/reference/expressions.html#dictionary-displays – Stefan Pochmann Nov 03 '17 at 09:13
  • @StefanPochmann: the behaviour in 2 is no different, although there was a bug where the value expression was evaluated before the key expression. – Martijn Pieters Nov 03 '17 at 09:14
  • @StefanPochmann: [Will a Python dict literal be evaluated in the order it is written?](//stackoverflow.com/q/28156687) – Martijn Pieters Nov 03 '17 at 09:15