Skip navigation

To create a new dictionary from an old one based on the dictionary values you can use this method:
>>> d
{‘foo’: None, ‘bar’: 3}
>>> dict(filter(lambda k: k[1], [(k,v) for k,v in d.iteritems()]))
{‘bar’: 3}

This creates a list of tuples:
>>>[(k,v) for k,v in d.iteritems()]
[(‘foo’, None), (‘bar’, 3)]

The filter method takes a function as its first argument that evaluates to True or False. In this instance this lambda function:
lambda k:k[1]will return True if the second item in the tuple evaluates to True, which in the case of (‘foo’,None) it does not.

You could create your own filter to search for whatever value you want.

dict() simply turns the list of tuples back into a dictionary, minus what the filter excluded.

Posted via email from Apphacker’s learning curve

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: