Tony Tony - 1 year ago 80
Python Question

How to remove a key from a dictionary?

When trying to delete a key from a dictionary, I write:

if 'key' in myDict:
del myDict['key']

Is there a one line way of doing this?

Answer Source

Use dict.pop():

my_dict.pop('key', None)

This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (ie. my_dict.pop('key')) and key does not exist, a KeyError is raised.

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