Standard for dict-contants with duplicate keys?

Peter Otten __peter__ at web.de
Fri Sep 15 17:47:00 EDT 2017


Tim Chase wrote:

> Looking through docs, I was unable to tease out whether there's a
> prescribed behavior for the results of defining a dictionary with the
> same keys multiple times
> 
>   d = {
>      "a": 0,
>      "a": 1,
>      "a": 2,
>       }
> 
> In my limited testing, it appears to always take the last one,
> resulting in
> 
>   {"a": 2}
> 
> as if it iterated over the items, adding them to the dict, tromping
> atop any previous matching keys in code-order.
> 
> Is this guaranteed by the language spec, or do I have a long weekend
> of data-cleaning ahead of me?  (this comes from an unwitting coworker
> creating such dicts that mung customer data, and I am trying to
> determine the extent of the damage...whether it's a consistent issue
> or is at the arbitrary whims of the parser)

Google finds stackoverflow quotes

"""
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.
"""

https://docs.python.org/3/reference/expressions.html#dictionary-displays




More information about the Python-list mailing list