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?
>>> 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.
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