Ogen
Ogen

Reputation: 6709

Why does python allow you to create dictionaries with duplicate keys

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?

Upvotes: 5

Views: 294

Answers (2)

laike9m
laike9m

Reputation: 19358

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

Upvotes: 6

Zizouz212
Zizouz212

Reputation: 4998

It doesn't. It just overwrites the keys.

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

Is it an error to overwrite a key? It shouldn't. Otherwise, you'd have a million errors when you try and update things in a dictionary. The reason for why I think there's no error is this (explaining 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.

Upvotes: 0

Related Questions