Tarrasch Tarrasch - 29 days ago 4x
Python Question

Mapping over values in a python dictionary

Given a dictionary

{ k1: v1, k2: v2 ... }
I want to get
{ k1: f(v1), k2: f(v2) ... }
provided I pass a function

Is there any such built in function? Or do I have to do

dict([(k, f(v)) for (k, v) in my_dictionary.iteritems()])

Ideally I would just write




That is, it doesn't matter to me if the original dictionary is mutated or a copy is created.


There is no such function; the easiest way to do this is to use a dict comprehension:

my_dictionary = {k: f(v) for k, v in my_dictionary.items()}

In python 2.7, use the .iteritems() method instead of .items() to save memory. The dict comprehension syntax wasn't introduced until python 2.7.

Note that there is no such method on lists either; you'd have to use a list comprehension or the map() function.

As such, you could use the map() function for processing your dict as well:

my_dictionary = dict(map(lambda (k,v): (k, f(v)), my_dictionary.iteritems()))

but that's not that readable, really.