Do keys that are the same override each other in a

2019-05-21 17:13发布

问题:

Keys must be unique in a dictionary, but I typed in the following assignment statement and it worked:

test = {'A1': 12, 'A1': 13, 'A1': 14}

and then testing it, I found

test['A1']
14

My question is: will dictionaries with the same key repeated multiple times choose the last occurring instance of that key when called? (i.e. Do the entries override each other)

回答1:

In Python, Dictionary storage is very interesting. Internally dictionaries are implemented using hash tables. So when you initialise a dictionary , these are the following steps that takes place in the background:

  • Internally PyDict_New() is called.
  • Allocation of new object
  • Few steps for getting available slots
  • While adding a new key/value pair it first searches for existing hash for the key. If it finds then use the same hash. So if you search for duplicate key , it fetches the lastest one.

Nice explanation for Python dictionary implementation http://www.laurentluce.com/posts/python-dictionary-implementation/