小能豆

How can I remove a key from a Python dictionary?

javascript

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?


阅读 203

收藏
2023-12-26

共1个答案

小能豆

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:

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.

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.

So, your code simplifies to:

my_dict.pop(key, None)

This is a concise and Pythonic way to achieve the same result without the need for an explicit if statement.

2023-12-26