How to Use Python Dictionary Comprehensions

Lists aren’t the only data type with comprehensions

How to Use Python Dictionary Comprehensions
Photo by Edho Pratama on Unsplash

One of Python’s most popular features is list comprehension — a low syntax, speedy alternative to looping through lists. But did you know comprehensions aren’t limited to lists?

Dictionary comprehensions, while not as pervasively used as list comprehensions, are a handy way to replace dictionary looping.


A Basic Dictionary Comprehension

To show the syntax of dictionary comprehensions, let’s go through a couple examples.

This first example will create a dictionary of values 1-10, where the term and definition are equivalent.my_nums = {
  i: i
  for i in range(1,6)
}print(my_nums) # {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5}

Next, let’s create the same dictionary but add a conditional filter to only create odd numbers.my_nums = {
  str(i): i
  for i in range(1,6)
  if i % 2 == 1
}
print(my_nums) # {'1': 1, '3': 3, '5': 5}

I know these two examples don’t make a lot of sense, but these vanilla examples are just to demonstrate the syntax.

The biggest difference between list and dictionary comprehensions is the need for two values with dictionaries (the term and the definition). Because of this subtle difference, dictionary comprehensions take an extra second to make sense and aren’t as frequently used.

Let’s move on to some real-world examples that’ll help get your creativity flowing.


Dictionary Comprehensions by Example

We’ll go over two dictionary comprehensions I’ve used in the past and keep in my active toolkit because they’re handy.

Removing null values

I love using dictionary comprehensions to remove null values — technically, None values. We take advantage of the conditional filter, and it looks something like this:data = {
 "id": 1,
 "first_name": "Jonathan",
 "middle_name": None,
 "last_name": "Hsu"
}cleaned = {
 k:v
 for (k,v) in data.items()
 if v != None
}"""
{
 'id': 1,
 'first_name': 'Jonathan',
 'last_name': 'Hsu'
}
"""

We use the .items() method of our original dictionary to return each key value pair as a two-value tuple that gets assigned to k and v respectively.

Replacement for map

I’ve learned to love the map method, but the reality is that dictionary comprehensions can often achieve the same results without the complexity of needing an additional method and lambdas.data = {
 "first_name": "Jonathan",
 "last_name": "Hsu"
}mapped = {
 k: v.upper()
 for (k,v) in data.items()
}"""
{
 'first_name': 'JONATHAN',
 'last_name': 'HSU'
}
"""


Conclusion

What are your favorite dictionary comprehensions? I hope this article gives you one more tool in your kit of skills.

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe