Mapping over dictionary values in Python

avatar

Borislav Hadzhiev

Thu Jun 16 20222 min read

Mapping over dictionary values in Python #

To map over a dictionary's values in Python:

  1. Use a dict comprehension to iterate over the dictionary's key-value pairs.
  2. On each iteration, pass the value as an argument to the function.
  3. The dict comprehension will perform the operation for every key-value pair.
main.py
my_dict = {'a': 1, 'b': 2, 'c': 3} def example_function(val): return val + 100 new_dict = { key: example_function(value) for key, value in my_dict.items() } print(new_dict) # 👉️ {'a': 101, 'b': 102, 'c': 103}

Dict comprehensions are very similar to list comprehensions.

They perform some operation for every key-value pair in the dictionary, or select a subset of key-value pairs that meet a condition.

In the example, we simply pass the value of the current iteration to the function.

An alternative approach is to use a for loop.

To map over a dictionary's keys:

  1. Declare a new variable that stores an empty dictionary.
  2. Use a for loop to iterate over the dictionary's items.
  3. On each iteration, call the function with the value.
  4. Assign the key-value pair to the new dictionary.
main.py
my_dict = {'a': 1, 'b': 2, 'c': 3} def example_function(val): return val + 100 new_dict = {} for key, value in my_dict.items(): new_dict[key] = example_function(value) print(new_dict) # 👉️ {'a': 101, 'b': 102, 'c': 103}

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

main.py
my_dict = {'id': 1, 'name': 'Alice'} print(my_dict.items()) # 👉️ dict_items([('id', 1), ('name', 'Alice')])

This gives us access to the key and the value in the for loop.

On each iteration, we call the function with the value and assign the key-value pair to the new dictionary.

This approach might be a bit easier to read if you aren't used to using dict comprehensions.

Use the search field on my Home Page to filter through my more than 1,000 articles.