Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does python allow you to create dictionaries with duplicate keys

Tags:

python

Dictionaries in python are supposed to have unique keys. Why are you allowed to do this...

d = {'a' : 'b', 'a' : 'c'}

Shouldn't this throw some sort of error?

like image 455
Ogen Avatar asked May 17 '15 02:05

Ogen


1 Answers

>>> d = {'a' : 'b', 'a' : 'c'}
>>> d
{'a': 'c'}

No, it's just you're initializing a dict using pre-existing key, which just over-writes the current value for the existing key.

>>> dis.dis("d = {'a' : 'b', 'a' : 'c'}")
  1           0 BUILD_MAP                2
              3 LOAD_CONST               0 ('b')
              6 LOAD_CONST               1 ('a')
              9 STORE_MAP
             10 LOAD_CONST               2 ('c')
             13 LOAD_CONST               1 ('a')
             16 STORE_MAP
             17 STORE_NAME               0 (d)
             20 LOAD_CONST               3 (None)
             23 RETURN_VALUE

>>> dis.dis("d={};d['a']='b';d['a']='c'")
  1           0 BUILD_MAP                0
              3 STORE_NAME               0 (d)
              6 LOAD_CONST               0 ('b')
              9 LOAD_NAME                0 (d)
             12 LOAD_CONST               1 ('a')
             15 STORE_SUBSCR
             16 LOAD_CONST               2 ('c')
             19 LOAD_NAME                0 (d)
             22 LOAD_CONST               1 ('a')
             25 STORE_SUBSCR
             26 LOAD_CONST               3 (None)
             29 RETURN_VALUE

As you can see, two ways of initializing are somewhat alike: first key-value is stored first then second.

like image 52
laike9m Avatar answered Nov 11 '22 15:11

laike9m