pythondictionary

Applying a function to values in dict


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


Solution

  • 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())