Borislav Hadzhiev
Thu Jun 16 2022·2 min read
Photo by Sandra Seitamaa
To map over a dictionary's values in Python:
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.
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:
for
loop to iterate over the dictionary's items.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).
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.