Note
Python - Dictionary (dict) Comprehensions - Create dictionaries with ease
Overview of Python Dictionary Comprehensions with Examples.
Dict Comprehensions in Python lets you quickly generate a dictionary from another iterable, similar to list comprehensions.
[<key_1>: <value_1> for <variable> in <iterable> if <expression_2>]
While doing so, you can optionally perform operations on keys and values going into your dict and also filter them based on conditions.
For the sake of completeness, please take a look at a note about Python List Comprehensions because they are very similar.
my_dict = {str(x): x for x in range(1, 6)}
print(my_dict) # {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5}
Output:
{'1': 1, '2': 2, '3': 3, '4': 4, '5': 5}
This is one of the simplest examples of dict comprehension. Keys are numbers from 1 to 5 as strings, and values are the same numbers but as integers.
Next, we will add filter condition that our dict elements will need to pass.
Adding a Condition in Dictionary Comprehensions
my_dict = {str(x): x for x in range(1, 6) if x % 2 == 0}
print(my_dict) # {'2': 2, '4': 4}
Output:
{'2': 2, '4': 4}
Here, we want in our dict, squares of integers that are even (divisible by 2 without any remain) from numbers 1 to 5 as a value. Keys are simply the same numbers but as a strings.
Splitting Dictionary Comprehensions in Multiple Lines for Readability
Like in list comprehensions, we can split them on more than one line to make them more readable.
my_dict = {f"square_{x}": x**2
for x in range(1, 6)
if x % 2 == 0}
print(my_dict) # {'square_2': 4, 'square_4': 16}
Output:
{'square_2': 4, 'square_4': 16}
And here we also did a little bit more interesting operations on keys and values of our dict.
Nested Dictionary Comprehensions (please, don't do this)
Dict comprehensions can be, of course, nested.
And they can access variables, methods, etc. from outer scopes.
In example below we used function items() on our nested dict comprehension to iterate over its keys and values at once.
def multiply_number(number: int, multiplier: int) -> int:
return number * multiplier
my_dict = {f'{x}*2': multiply_number(y, 2) for x, y in {str(x): x for x in range(1, 10) if x % 2 == 0}.items() if y % 4 == 0}
print(my_dict) # {'4*2': 8, '8*2': 16}
my_dict = {f'{x}*2': multiply_number(y, 2)
for x, y in {str(x): x for x in range(1, 10) if x % 2 == 0}.items()
if y % 4 == 0}
print(my_dict) # {'4*2': 8, '8*2': 16}
Output:
{'4*2': 8, '8*2': 16}
{'4*2': 8, '8*2': 16}
Notice that we also added yet another if statement that our y value needs to be divisible by 4 without remaining.
Do not confuse it with the first if statement that checks if x is even in first, nested dict comprehension.
The same as with list comprehensions, you can see that nested and more complicated comprehensions can quickly become very hard to read. Remember that using comprehensions is not worth it if another developer reading our code has a tough time understanding it.
Key Points to Remember about Dictionary Comprehensions
-
Versatility: Dictionary comprehensions allow for concise dictionary creation, supporting operations and filters on both keys and values.
-
Readability: For complex comprehensions, consider splitting lines and/or avoiding excessive nesting for readability. Also, you could simply avoid complex comprehensions in general.
-
Use of Conditions: Multiple conditions can be applied, but complex conditions can make the comprehension difficult to read.
I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!
You might also be interested in:
- 💡 Python - isdigit() - Check if a string contains only digits
- 💡 Python - count() - Count occurrences of an element in a collection
- 💡 Python - Counter Dict - Simplify counting with collections
- 💡 Python - Default Dict - Simplify handling of missing keys in dictionaries
- 💡 Python - List, Tuple, and Set Comprehensions - Simplify iterable transformations