We've talked about list and set comprehensions before. Comprehensions are great, and we should use them more.
The third and final type of comprehension in Python is dict comprehension.
Dict comprehensionPermalink
Dict comprehension creates a dict using an existing iterable as an input.
Dict comprehension has two differences from list comprehension.
- We use curly brackets
{}
instead of square brackets[]
(yes, same brackets as for set comprehension). - Since dict needs key and value for each entry, our comprehension needs to return both. We do it by separating them with a colon
:
.
Let's have a look at how it works.
Say we have a list of numbers. We want to calculate squares for our numbers and store them in dict where the key will be our number and the value will be its square.
We can do it with dict comprehension like this:
numbers = [1, 2, 3, 4, 5]
{n: n * n for n in numbers}
# outputs: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Here is a more visual explanation:
We could also rewrite dict comprehension into a normal for loop like this:
number_squared = {}
for n in numbers:
number_squared[n] = n * n
And this is how the above for loop translates to the dict comprehension:
As with list comprehension, we can also filter which items from our input iterable we want to use. We just need to add if
at the end of our comprehension.
Here we will square only even numbers:
numbers = [1, 2, 3, 4, 5]
{n: n * n for n in numbers if n % 2 ==0}
# outputs: {2: 4, 4: 16}
SummaryPermalink
Dict comprehensions work similarly to list comprehensions but:
- They create a dict (not a list).
- They start and end with curly brackets
{}
instead of square brackets[]
. - They require using colon
:
between key and value we are returning from comprehension. - That colon
:
distinguishes them from set comprehensions that also use curly brackets.
Happy coding!
You might also like
Better Python apps in AWS with stelvio.dev
Deep dives and quick insights into cloud architecture.