This article shows you how to apply a given function to each element of a Python dictionary.
The most Pythonic way to apply a function to each element of a Python dict
is combining the dictionary comprehension feature and the dict.items()
method like so:
{k:f(v) for k,v in dict.items()}
Note: All the solutions provided below have been verified in Python 3.9.5.
Problem Formulation
Imagine the following dictionary of age values:
my_dict = {'alice': 18, 'bob': 20, 'carl': 25}
How to apply a function f(x) = x + 1 to increment each value by one—in our example increment the age as a year goes by?
{'alice': 19, 'bob': 21, 'carl': 26}
I’ll start with the “naive approach” first and show you the more Pythonic solutions afterward. So, let’s get started!
Method 1: Simple For Loop
The above problem, like many others, has quite a simple solution in Python.
A simple solution uses a vanilla Python loop to iterate over each key
:value
pair of the original dictionary. In the loop body, you then apply the function to each value and assign the result back to the key.
Assume we have the following function that we want to apply to each element in the dictionary:
def f(x): ''' Function to apply to each dict element.''' return x + 1
Here’s how you can apply this function to each dictionary value in a simple for loop:
my_dict = {'alice': 18, 'bob': 20, 'carl': 25} for k,v in my_dict.items(): my_dict[k] = f(v) print(my_dict) # {'alice': 19, 'bob': 21, 'carl': 26}
However, this is not the most Pythonic way to approach this problem.
Method 2: Dictionary Comprehension
The most Pythonic way to apply a function f
to each value of a dictionary is to use a dictionary comprehension and dict.items()
to iterate over each key:value
pair of a given dictionary.
{k:f(v) for k,v in dict.items()}
Let’s say we use the function f
defined in the previous section. Here’s how to apply function f
to each value of the dictionary my_dict
:
my_dict = {'alice': 18, 'bob': 20, 'carl': 25} my_dict = {k:f(v) for k,v in my_dict.items()} print(my_dict) # {'alice': 19, 'bob': 21, 'carl': 26}
Dictionary comprehension is a concise and memory-efficient way to create and initialize dictionaries in one line of Python code.
It consists of two parts: expression and context.
- The expression defines how to map keys to values.
- The context loops over an iterable using a single-line for loop and defines which
key:value
pairs to include in the new dictionary.
To learn more about the beautiful feature of dictionary comprehension, feel free to watch the following explainer video:
And to learn more about the dict.items()
method, feel free to watch the following tutorial video:
β‘ Performance Note: Compared to the simple for loop, this approach actually creates a new dictionary object which is less memory efficient. For large dictionaries, I’d recommend you use the simple for loop and update the dictionary values one by one.
Method 3: map() Function
For comprehensibility, I’d like to suggest an alternative to solve this problem—however, don’t use it! The previous method is far more Pythonic and more readable!
Everything is the same as before except the highlighted line:
dict(zip(my_dict.keys(), map(f, my_dict.values())))
def f(x): ''' Function to apply to each dict element.''' return x + 1 my_dict = {'alice': 18, 'bob': 20, 'carl': 25} my_dict = dict(zip(my_dict.keys(), map(f, my_dict.values()))) print(my_dict) # {'alice': 19, 'bob': 21, 'carl': 26}
Let’s dive into all the concepts used in the one-liner solution:
- You use the
dict()
function to create a new dictionary. - You zip together the keys and new values (after applying the function
f
) into a list of(key, value)
tuples. - You use the
dict.keys()
method to obtain all dictionary keys from the original dictionary. - You use the
dict.values()
method to obtain the dictionary values from the original dictionary. - You use the
map()
function to apply functionf
to each value in the dictionary.
Due to the many concepts included in this one-liner, I think the educational benefit of studying the one-liner overcompensates for the slight confusion you may experience when reading over it the first time. π
If you liked the one-liners presented in this article, you’ll love my book about Python One-Liners:
Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
You’ll also learn how to:
- Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
- Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
- Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
- Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
- Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.