Duplicate dictionary keys in initialization - Python

Viewed 326

Is it correct to say that the rightmost/last key-value pair for a given key would always be considered if there are multiple identical keys when initializing a dictionary ?

Example :

Dict = {'A': 5, 'B': 6, 'A': 10}

Will Dict['A'] always be 10 in all python implementations? Where does python enforce this ?

2 Answers

You know that python dict can't contain duplicate keys. So

Dict = {'A': 5, 'B': 6)
Dict.update({'A': 10})
print(Dict['A'])

will result in the last value assigned to the key A:

Output:

10

So the situation is almost like that, python goes through the dictionary during evaluation, and keeps the last value assigned to the keys.


I know dict aren't ordered, but:

  • That doesn't mean python will jump back and forth on the dict when parsing the dict into memory.

  • It will parse through it from left to right to get the collect the data, but it stores the dict without keeping its order.

Python dict can not have duplicate keys. if you try to add the same key again, it will update the existing key with the new value.

Dict = {'A': 5, 'B': 6, 'A': 10}
print(Dict)
{'A': 10, 'B': 6}

the above statement execution is similar to below:

Dict['A'] = 5    
print(Dict)
{'A'=5}

Dict['B'] = 6 
print(Dict)
{'A'=5, 'B'=6}

Dict['A'] = 10
print(Dict)
{'A'=10, 'B'=6}
Related