Silently removing key from a python dict

Question:

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?

Asked By: Ozgur Vatansever

||

Answers:

The following will delete the keys, if they are present, and it won’t throw an error:

for d in [None, '']:
    if d in my_dict:
        del my_dict[d]
Answered By: Simeon Visser

You could use the dict.pop method and ignore the result:

for key in [None, '']:
    d.pop(key, None)
Answered By: Jon Clements

You can do this:

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

Pops dictionary with a default value that you ignore.

Answered By: Keith

You can try:

d = dict((k, v) for k,v in d.items() if k is not None and k != '')

or to remove all empty-like keys

d = dict((k, v) for k,v in d.items() if k )
Answered By: Maksym Polshcha
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.