How I can get rid of None values in dictionary?

d = {'a': None, 'b': 'myname', 'c': 122}
print dict(filter(lambda x:x[1], d.items()))
{'b': 'myname', 'c': 122}

I like the variation of your second method:

   res = dict((a, b) for (a, b) in kwargs.iteritems() if b is not None)

it's Pythonic and I don't think that ugly. A variation of your first is:

   for (a, b) in list(kwargs.iteritems()):
       if b is None:
            del kwargs[a]

Another way to write it is

res = dict((k,v) for k,v in kwargs.iteritems() if v is not None)

In Python3, this becomes

res = {k:v for k,v in kwargs.items() if v is not None}

You can also use filter:

d = dict(a = 1, b = None, c = 3)

filtered = dict(filter(lambda item: item[1] is not None, d.items()))

print(filtered)
{'a': 1, 'c': 3}

Tags:

Python