如何通过d[key] = val防止创建密钥



假设我有d = {'dogs': 3}。使用:

d['cats'] = 2 

将创建密钥'cats'并为其赋值2

如果我真的打算用一个新的键和值更新一个字典,我将使用d.update(cats=2),因为它感觉更明确。

自动创建键容易出错(特别是在较大的程序中),例如:

# I decide to make a change to my dict.
d = {'puppies': 4, 'big_dogs': 2}

# Lots and lots of code.
# ....
def change_my_dogs_to_maximum_room_capacity():
    # But I forgot to change this as well and there is no error to inform me.
    # Instead a bug was created.
    d['dogs'] = 1

问题:
是否有一种方法可以通过d[key] = value禁用不存在的密钥的自动创建,而是引发KeyError ?

其他的应该继续工作:

d = new_dict()                  # Works
d = new_dict(hi=1)              # Works
d.update(c=5, x=2)              # Works
d.setdefault('9', 'something')  # Works
d['a_new_key'] = 1              # Raises KeyError

您可以使用一个特殊的__setitem__方法创建dict的子节点,该方法拒绝初始创建时不存在的键:

class StrictDict(dict):
    def __setitem__(self, key, value):
        if key not in self:
            raise KeyError("{} is not a legal key of this StricDict".format(repr(key)))
        dict.__setitem__(self, key, value)
x = StrictDict({'puppies': 4, 'big_dogs': 2})
x["puppies"] = 23 #this works
x["dogs"] = 42    #this raises an exception

它不是完全无懈可击的(例如,它允许x.update({"cats": 99})无投诉),但它防止了最可能发生的情况。

继承dict类并覆盖__setitem__以满足您的需要。试试这个

class mydict(dict):
    def __init__(self, *args, **kwargs):
        self.update(*args, **kwargs)
    def __setitem__(self, key, value):
        raise KeyError(key)
>>>a=mydict({'a':3})
>>>d
{'a': 3}
>>>d['a']
3
>>>d['b']=4
KeyError: 'b'

这将只允许使用update:

添加key=value的新密钥
 class MyDict(dict):
    def __init__(self, d):
        dict.__init__(self)
        self.instant = False
        self.update(d)
    def update(self, other=None, **kwargs):
        if other is not None:
            if isinstance(other, dict):
                for k, v in other.items():
                    self[k] = v
            else:
                for k, v in other:
                    self[k] = v
        else:
            dict.update(self, kwargs)
        self.instant = True
    def __setitem__(self, key, value):
        if self.instant and key not in self:
            raise KeyError(key)
        dict.__setitem__(self, key, value)
x = MyDict({1:2,2:3})
x[1] = 100 # works
x.update(cat=1) # works
x.update({2:200}) # works 
x["bar"] = 3 # error
x.update({"foo":2}) # error
x.update([(5,2),(3,4)])  # error

最新更新