Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silently removing key from a python dict [duplicate]

I have a python dict and I'd like to silently remove either None and '' keys from my dictionary so I came up with something like this:

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

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?

like image 503
Ozgur Vatansever Avatar asked Jul 06 '12 08:07

Ozgur Vatansever


People also ask

How do you remove duplicate keys in Python?

You can remove duplicates from a Python using the dict. fromkeys(), which generates a dictionary that removes any duplicate values. You can also convert a list to a set.

Can you remove a key from a dictionary Python?

To remove a key from a dictionary in Python, use the pop() method or the “del” keyword. Both methods work the same in that they remove keys from a dictionary. The pop() method accepts a key name as argument whereas “del” accepts a dictionary item after the del keyword.


1 Answers

You can do this:

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

Pops dictionary with a default value that you ignore.

like image 190
Keith Avatar answered Oct 10 '22 19:10

Keith