map() over Python’s dictionary

Posted: August 3rd, 2010 | Author: | Filed under: Python | Tags: , , , , | No Comments »

Well, it isn’t really possible – but if we transform the dictionary into a list of key-value tuples (using iteritems()), use map on that regular list, and than transform it back into a dictionary (using dict()), we can get it to work quite nicely.

Here’s how it looks:

>>> dict(map(lambda (k,v): (k,v+1), {'foo':123,'hello':456,'lorem':789}.iteritems()))
{'foo': 124, 'lorem': 790, 'hello': 457}

I even made a small lambda function to make it quicker:

>>> dmap = lambda l,d: dict(map(l, d.iteritems()))
>>> dmap(lambda (k,v): (k,v+1), {'foo':123,'hello':456,'lorem':789})
{'foo': 124, 'lorem': 790, 'hello': 457}