81

I want to apply a function to all values in dict and store that in a separate dict. I am just trying to see how I can play with python and want to see how I can rewrite something like this

for i in d:
    d2[i] = f(d[i])

to something like

d2[i] = f(d[i]) for i in d

The first way of writing it is of course fine, but I am trying to figure how python syntax can be changed

4 Answers 4

120

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())
4
  • 32
    +1. Note that this is creating a new dictionary d2 instead of modifying one in place. But this is almost always what you actually want to do. If you really do need to update d2 in place, you can always do d2.update({k: f(v) for k, v in d1.items()}).
    – abarnert
    Commented Oct 25, 2012 at 7:36
  • using 3.x and the second approach works nicely. exactly what I was looking for. thanks
    – chrise
    Commented Oct 25, 2012 at 10:55
  • thanks for your comment abarnert. I need to create a new dict in this case, but good to know this for other cases. thanks
    – chrise
    Commented Oct 25, 2012 at 10:55
  • @abarnert, is it possible to update the dictionary to map a function to the values of user-specifed keys rather than all keys? Commented Dec 20, 2018 at 21:08
9

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.

0
6
d2 = dict((k, f(v)) for k,v in d.items())
5

Dictionaries can be nested in Python and in this case the solution d2 = {k: f(v) for k, v in d1.items()} will not work.

For nested dictionaries one needs some function to transverse the whole data structure. For instance if values are allowed to be themselves dictionaries, one can define a function like:

def myfun(d):
  for k, v in d.iteritems():
    if isinstance(v, dict):
      d[k] = myfun(v)
    else:
      d[k] = f(v)
  return d

And then

d2 = myfun(d)

Not the answer you're looking for? Browse other questions tagged or ask your own question.