Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove a key from a Python dictionary?

When deleting a key from a dictionary, I use:

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

Is there a one line way of doing this?

like image 722
Tony Avatar asked Jun 30 '12 20:06

Tony


People also ask

How do I remove a key from a list in Python?

In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.

What is the wrong way of deleting the value of key key from a dictionary in Python?

If you call pop() on a key that doesn't exist, Python would return a KeyError . So only use pop(key) if you're confident that the key exists in the dictionary. If you are unsure if the key exists then put a value for the second, optional argument for pop() - the default value.


2 Answers

To delete a key regardless of whether it is in the dictionary, use the two-argument form of 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 (i.e. my_dict.pop('key')) and key does not exist, a KeyError is raised.

To delete a key that is guaranteed to exist, you can also use:

del my_dict['key'] 

This will raise a KeyError if the key is not in the dictionary.

like image 94
Sven Marnach Avatar answered Oct 03 '22 20:10

Sven Marnach


Specifically to answer "is there a one line way of doing this?"

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

...well, you asked ;-)

You should consider, though, that this way of deleting an object from a dict is not atomic—it is possible that 'key' may be in my_dict during the if statement, but may be deleted before del is executed, in which case del will fail with a KeyError. Given this, it would be safest to either use dict.pop or something along the lines of

try:     del my_dict['key'] except KeyError:     pass 

which, of course, is definitely not a one-liner.

like image 44
zigg Avatar answered Oct 03 '22 22:10

zigg