How can I force a dictionary in python to reject u

2020-06-16 02:50发布

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

4条回答
唯我独甜
2楼-- · 2020-06-16 03:22

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")
查看更多
Luminary・发光体
3楼-- · 2020-06-16 03:22

Just check your dict before you add the item

if 'k' not in mydict:
    mydict.update(myitem)
查看更多
狗以群分
4楼-- · 2020-06-16 03:40

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}
查看更多
老娘就宠你
5楼-- · 2020-06-16 03:44

You could create a custom dictionary by deriving from dict and overriding __setitem__ to reject items already in the dictionary.

查看更多
登录 后发表回答