Why python allows you to create dictionaries with duplicate keys

Dictionaries in python must have unique keys. Why are you allowing this to be done ...

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

Shouldn't that cause some kind of error?

+5
source share
2 answers
 >>> d = {'a' : 'b', 'a' : 'c'} >>> d {'a': 'c'} 

No, it's just that you initialize the dict using an already existing key, which simply overwrites 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, the two initialization methods are somewhat similar: the first key value is stored first, and then the second.

+6
source

This is not true. It just overwrites the keys.

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

Is it wrong to rewrite the key? It should not. Otherwise, you will have a million errors when trying to update the contents in the dictionary. The reason why I think there is no error in this (explanatory code in English):

  d is a dictionary.
 there is a key and a value.  ('a' and 'b')
 Pair them up and enter them, while saving them.
 New entry ('a' and 'c')
 key 'a' already exists;  update value.
0
source

All Articles