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.)
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
a = {0: 1, 0: 2}
a[0]
2
It will give the value of highest index in the same or duplicate key's value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With