简体   繁体   English

有没有办法更新 Python 字典的值,但如果它不存在则不添加键?

[英]Is there a way to update the value of a Python dictionary but not add the key if it doesn't exist?

I have a dictionary as such:我有一本这样的字典:

d = {'a': 1, 'b': 2, 'c': 3}

I want to update the value of key 'c' and can do that with d['c'] = 30 .我想更新键'c'的值,并且可以使用d['c'] = 30来做到这一点。

The behavior I want is to only be able to update existing keys, not add new keys.我想要的行为是只能更新现有密钥,不能添加新密钥。 If I try to do d['e'] = 4 I would like it to throw some kind of exception instead of the default behavior which is to create a new key 'e' with value 4 .如果我尝试做d['e'] = 4我希望它抛出某种异常而不是默认行为,即创建一个值为4的新键'e'

Is there a function that does such behavior?有没有做这种行为的 function ? I know I can do a comprehension to first check if 'e' in d but again, checking if there's a built-in.我知道我可以做一个理解,首先检查if 'e' in d然后再检查是否有内置的。

I'm not aware of such behavior built-in, but you could always implement your own dict:我不知道内置的这种行为,但你总是可以实现你自己的字典:

class no_new_dict(dict):
    def __setitem__(self, key, value):
        if key in self:
            super().__setitem__(key, value)
        else:
            raise KeyError(key)

d = no_new_dict({'a': 1, 'b': 2, 'c': 3})
print(d)
d['c'] = 20
print(d)
d['d'] = 20

The output of the above snippet will be:上述代码段的 output 将是:

{'a': 1, 'b': 2, 'c': 3}
{'a': 1, 'b': 2, 'c': 20}
Traceback (most recent call last):
  File "C:\Users\tomerk\PycharmProjects\pythonProject\test.py", line 12, in <module>
    d['d'] = 20
  File "C:\Users\tomerk\PycharmProjects\pythonProject\test.py", line 6, in __setitem__
    raise KeyError(key)
KeyError: 'd'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM