What is the proper way to remove keys from a dictionary with value == None
in Python?
You can also do this using the del command
f = {};
f['win']=None
f
=> {'win': None}
del f['win']
Or if you want this in a function format you could do:
def del_none_keys(dict):
for elem in dict.keys():
if dict[elem] == None:
del dict[elem]
Generally, you'll create a new dict
constructed from filtering the old one. dictionary comprehensions are great for this sort of thing:
{k: v for k, v in original.items() if v is not None}
If you must update the original dict, you can do it like this ...
filtered = {k: v for k, v in original.items() if v is not None}
original.clear()
original.update(filtered)
This is probably the most "clean" way to remove them in-place that I can think of (it isn't safe to modify a dict while you're iterating over it)
Use original.iteritems()
on python2.x
You could also take a copy of the dict
to avoid iterating the original dict
while altering it.
for k, v in dict(d).items():
if v is None:
del d[k]
But that might not be a great idea for larger dictionaries.
For python 2.x
:
dict((k, v) for k, v in original.items() if v is not None)
Maybe you'll find it useful:
def clear_dict(d):
if d is None:
return None
elif isinstance(d, list):
return list(filter(lambda x: x is not None, map(clear_dict, d)))
elif not isinstance(d, dict):
return d
else:
r = dict(
filter(lambda x: x[1] is not None,
map(lambda x: (x[0], clear_dict(x[1])),
d.items())))
if not bool(r):
return None
return r
it would:
clear_dict(
{'a': 'b', 'c': {'d': [{'e': None}, {'f': 'g', 'h': None}]}}
)
->
{'a': 'b', 'c': {'d': [{'f': 'g'}]}}
if you don't want to make a copy
for k,v in list(foo.items()):
if v is None:
del foo[k]