Home > Mobile >  Add element to dict but don't overwrite value when key exists
Add element to dict but don't overwrite value when key exists

Time:07-28

I want to add elements (key-value-pairs) to a dict. But I want to prevent overwriting existing values when the key exists.

But I don't want to do an if check. 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

CodePudding user response:

You can subclass dict and in particular, override the __setitem__ method.

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

CodePudding user response:

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:

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'

CodePudding user response:

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')
  • Related