Applying a function to values in dict
d2 = dict((k, f(v)) for k,v in d.items())
If you're using Python 2.7 or 3.x:
d2 = {k: f(v) for k, v in d1.items()}
Which is equivalent to:
d2 = {}
for k, v in d1.items():
d2[k] = f(v)
Otherwise:
d2 = dict((k, f(v)) for k, v in d1.items())
You could use map
:
d2 = dict(d, map(f, d.values()))
If you don't mind using an extension. You can also use valmap
in the toolz library which is functionally equivalent to using the map
solution:
from toolz.dicttoolz import valmap
d2 = valmap(f, d)
If not for the clean presentation of the method, you also have the option of supplying a default return class as well, for people that need something other than a dict
.