Silently removing key from a python dict

PythonDictionary

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

You can do this:

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

Pops dictionary with a default value that you ignore.

Solution 2 - Python

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

for key in [None, '']:
    d.pop(key, None)

Solution 3 - Python

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]

Solution 4 - Python

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 )

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOzgur VatanseverView Question on Stackoverflow
Solution 1 - PythonKeithView Answer on Stackoverflow
Solution 2 - PythonJon ClementsView Answer on Stackoverflow
Solution 3 - PythonSimeon VisserView Answer on Stackoverflow
Solution 4 - PythonMaksym PolshchaView Answer on Stackoverflow