简体   繁体   English

将元素添加到 dict 但当键存在时不覆盖值

[英]Add element to dict but don't overwrite value when key exists

I want to add elements (key-value-pairs) to a dict .我想将元素(键值对)添加到dict But I want to prevent overwriting existing values when the key exists.但是我想防止在密钥存在时覆盖现有值。

But I don't want to do an if check.但我不想做一个if检查。 I would prefer an exception.我宁愿有个例外。

d = {}

d['a'] = 1
d['b'] = 2
d['a'] = 3  # <-- raise Exception! "KeyExistsException'

What I don't want我不想要的

if not 'a' in d:
    d['a'] = 3

You can subclass dict and in particular, override the __setitem__ method.您可以继承dict ,特别是覆盖__setitem__方法。

This sounds like what you want:这听起来像你想要的:

class SpecialDict(dict):
    def __setitem__(self, key, value):
        if not key in self:
            super(SpecialDict, self).__setitem__(key, value)
        else:
            raise Exception("Cannot overwrite key!") # You can make your own type here if needed


x = SpecialDict()


x['a'] = 1
x['b'] = 2
x['a'] = 3  #raises Exception

Instead of subclassing dict as suggested by JacobIRR, you could also define a helper function for storing a key-value pair in a dict that throws an exception when the key already exists:除了按照 JacobIRR 的建议对dict进行子类化,您还可以定义一个帮助器 function 用于将键值对存储在 dict 中,当键已经存在时会引发异常:

class KeyExistsException(Exception):
    pass

def my_add(the_dict, the_key, the_value):
    if the_key in the_dict:
        raise KeyExistsException("value already exists")
    the_dict[the_key] = the_value


d = {}

my_add(d, 'a', 1)
my_add(d, 'b', 2)
my_add(d, 'a', 3)  # <-- raise Exception! "KeyExistsException'

This might work for your use.这可能对您有用。 I am a noob so I may be overlooking something.我是菜鸟,所以我可能会忽略一些东西。

d = {}
 
try:
    d['new_key']  # check if key exists.
except KeyError:  # if not exist create.
    d['new_key'] = 'value'
else:  # else raise exception KeyExists.
    raise Exception ('KeyExists')

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

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