TomNash
TomNash

Reputation: 3288

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.

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.

Is there a function that does such behavior? I know I can do a comprehension to first check if 'e' in d but again, checking if there's a built-in.

Upvotes: 2

Views: 567

Answers (1)

Tomerikoo
Tomerikoo

Reputation: 19414

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:

{'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'

Upvotes: 2

Related Questions