Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: modify existing key-value pair and raising exception if key does not exist

Tags:

python

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.

like image 590
Advait Avatar asked Mar 24 '23 04:03

Advait


1 Answers

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]
like image 197
piokuc Avatar answered Apr 25 '23 07:04

piokuc