Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force a dictionary in python to reject updates of existing keys?

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

like image 224
Hossein Avatar asked May 10 '11 09:05

Hossein


2 Answers

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}
like image 37
user2197172 Avatar answered Oct 07 '22 20:10

user2197172


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")
like image 164
Jakob Bowyer Avatar answered Oct 07 '22 19:10

Jakob Bowyer