ozgur ozgur - 1 year ago 150
Python Question

silently remove key from a python dict

I have a python dict and I'd like to silently remove either

keys from my dictionary so I came up with something like this:

del my_dict[None]
except KeyError:

del my_dict['']
except KeyError:

As you see, it is less readable and it causes me to write duplicate code. So I want to know if there is a method in python to remove any key from a dict without throwing a key error?

Answer Source

You can do this:

d.pop("", None)
d.pop(None, None)

Pops dictionary with a default value that you ignore.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download