Is it possible to design a dictionary in Python in a way that if by mistake a key which is already in the dictionary is added, it gets rejected? thanks
This is the purpose of setdefault:
>>> x = {}
>>> print x.setdefault.__doc__
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
>>> x.setdefault('a', 5)
5
>>> x
{'a': 5}
>>> x.setdefault('a', 10)
5
>>> x
{'a': 5}
This also means you can skip "if 'key' in dict: ... else: ..."
>>> for val in range(10):
... x.setdefault('total', 0)
... x['total']+=val
...
0
0
1
3
6
10
15
21
28
36
>>> x
{'a': 5, 'total': 45}
You can always create your own dictionary
class UniqueDict(dict):
def __setitem__(self, key, value):
if key not in self:
dict.__setitem__(self, key, value)
else:
raise KeyError("Key already exists")
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