Standard for dict-contants with duplicate keys?

Terry Reedy tjreedy at udel.edu
Fri Sep 15 17:45:22 EDT 2017


On 9/15/2017 3:36 PM, 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,

https://docs.python.org/3/reference/expressions.html#dictionary-displays
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.

  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)
> 
> Thanks,
> 
> -tkc
> 
> 
> 
> 


-- 
Terry Jan Reedy





More information about the Python-list mailing list