Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do keys that are the same override each other in a dictionary in Python?

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)

like image 962
Jeffrey Y. Avatar asked Sep 14 '25 10:09

Jeffrey Y.


1 Answers

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/

like image 98
abhinav kumar Avatar answered Sep 15 '25 23:09

abhinav kumar