开发者

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

开发者 https://www.devze.com 2023-03-04 16:06 出处:网络
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?

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开发者_如何学编程


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")


Just check your dict before you add the item

if 'k' not in mydict:
    mydict.update(myitem)


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 could create a custom dictionary by deriving from dict and overriding __setitem__ to reject items already in the dictionary.

0

精彩评论

暂无评论...
验证码 换一张
取 消