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

How to prevent key creation through 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 class 并覆盖 __setitem__ 以适合您的 needs.Try this

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'

这将只允许使用更新 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