Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a dict literal containing repeated keys well-defined?

If I write d = {0: 1, 0: 2}, does Python guarantee the value of d[0], or is it "undefined behavior"?

(Of course, this isn't something you'd ever write when programming, but this question is mostly out of curiosity. Locally, it seems to always save the value associated with the key's last occurrence, i.e. 2 here. Maybe it's useful info for some weird code gen situations, though.)

like image 645
Lynn Avatar asked Sep 15 '25 04:09

Lynn


2 Answers

yes, it is well-defined -- last value wins. {0: 1, 0: 2} is a dictionary display:

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.emphasis is mine

like image 189
jfs Avatar answered Sep 16 '25 18:09

jfs


a = {0: 1, 0: 2}
a[0]
2

It will give the value of highest index in the same or duplicate key's value

like image 28
sathish Avatar answered Sep 16 '25 16:09

sathish