tags:

views:

98

answers:

3

Something like:

for (a,b) in kwargs.iteritems():
    if not b : del kwargs[a]

This code raise exception because changing of dictionary when iterating.

I discover only non pretty solution with another dictionary:

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

Thanks

+4  A: 

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]
rlotun
You can just use kwargs.items(), which already returns a list.
liori
`dict.items()` no longer returns a list in Python3. It works more like `iteritems()`
gnibbler
+7  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)}
gnibbler
A: 

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}
Luiz Damim