This post will discuss how to apply a function to each item of dictionary in Python.

We need to apply a mapping function f(x) to a dictionary { k1: v1, k2: v2, … , kn: vn} which should result in dictionary { k1: f(v1), k2: f(v2), … , kn: f(vn)}.

1. Using Dictionary Comprehension

A simple and fairly efficient way to apply a mapping function to each key/value pair of a dictionary is with dictionary comprehension, as shown below:

Download  Run Code

2. Using for-loop

If you need to perform the mapping in-place rather than creating a new dictionary, you can do so with a simple for-loop. This is demonstrated below:

Download  Run Code

3. Using toolz.valmap() function

The toolz library offers several utility functions for iterators, functions, and dictionaries. You can use the toolz.valmap() function to apply a function to the dictionary’s values. Similarly, to apply function to keys of a dictionary, use toolz.keymap() function and to apply function to items of a dictionary, use toolz.itemmap() function.

Download Code

4. Using map() function

The in-built map() function provides a convenient way to apply a function to every item of iterable. You can use it for applying a mapping to the dictionary as well. You can use this as:

Download  Run Code

That’s all about applying a function to each item of the dictionary in Python.