Apply a function to each item of a Python dictionary
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:
|
1 2 3 4 5 6 7 8 9 10 |
def f(x): return x + 1 if __name__ == '__main__': d = {'A': 0, 'B': 1, 'C': 2} dict = {k: f(v) for k, v in d.items()} print(dict) # {'A': 1, 'B': 2, 'C': 3} |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
def f(x): return x + 1 if __name__ == '__main__': d = {'A': 0, 'B': 1, 'C': 2} for k, v in d.items(): d[k] = f(v) print(d) # {'A': 1, 'B': 2, 'C': 3} # {'A': 1, 'B': 2, 'C': 3} |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import toolz def f(x): return x + 1 if __name__ == '__main__': d = {'A': 0, 'B': 1, 'C': 2} dict = toolz.valmap(f, d) print(dict) # {'A': 1, 'B': 2, 'C': 3} |
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:
|
1 2 3 4 5 6 7 8 9 10 |
def f(x): return x + 1 if __name__ == '__main__': d = {'A': 0, 'B': 1, 'C': 2} dict = dict(map(lambda x: (x[0], f(x[1])), d.items())) print(dict) # {'A': 1, 'B': 2, 'C': 3} |
That’s all about applying a function to each item of the dictionary in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)