How can I force a dictionary in python to reject u

2020-06-16 03: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? thanks

回答1:

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


回答2:

Just check your dict before you add the item

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


回答3:

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}


回答4:

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