I want to remove a key from a dictionary if it is present. I currently use this code:
if key in my_dict: del my_dict[key]
Without the if statement, the code will raise KeyError if the key is not present. How can I handle this more simply?
if
KeyError
You can use the dict.pop() method with a default value to remove a key from a dictionary if it is present and avoid raising a KeyError if the key is not found. Here’s an example:
dict.pop()
my_dict.pop(key, None)
This one-liner will remove the key key from my_dict if it exists, and if it doesn’t, it will do nothing without raising an error.
key
my_dict
The second argument to pop() is the default value to return if the key is not found. Since you want to do nothing in that case, None is used here.
pop()
None
So, your code simplifies to:
This is a concise and Pythonic way to achieve the same result without the need for an explicit if statement.