I'd like to only change the value of a key in a dictionary if it already exists.
I could do this with the following function but am wondering if there is a more concise way of doing this.
def modify_existing_key_value(d, key, new_value):
if key in d:
d[key] = new_value
else:
raise KeyError(k)
The use case is to inadvertently avoid creating new key-value pairs in the dictionary.
Just try to access the element using the key, if it's there, nothing happens, and so the execution proceeds to the next instruction which resets the value, otherwise KeyError
exception will be raised, as you want it:
def modify_existing_key_value(d, key, new_value):
d[key] # We don't need the old value, just checking the key
d[key] = new_value
The whole purpose of the first line of the function:
d[key]
is to raise KeyError
exception if the dictionary doesn't contain the key.
Using d[key] to raise KeyError
exception, a one-liner could be:
d[key] = new_value if key in d else d[key]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With