Blog Post #72: A Glimpse of the Future: An Introduction to Dictionary Comprehensions

So far, we’ve learned to build dictionaries by manually defining them or by adding key-value pairs one by one. These methods work perfectly, but as you become more advanced in Python, you’ll discover more concise and powerful ways to accomplish common tasks.

In this post, we’ll get a glimpse of a more advanced topic known as comprehensions. Specifically, we will introduce the dictionary comprehension, a “Pythonic” one-liner for creating dictionaries from existing iterables.

The for Loop Method: Creating a Dictionary

Let’s say we have a list of numbers and we want to create a dictionary where the keys are the numbers and the values are their squares. Using the for loop and assignment syntax we already know, the code would look like this:

numbers = [1, 2, 3, 4]
squares_dict = {} # Start with an empty dictionary

for number in numbers:
    squares_dict[number] = number ** 2

print(squares_dict)

This code is clear and works perfectly, producing {1: 1, 2: 4, 3: 9, 4: 16}. But this pattern—start with an empty container, loop through an iterable, and add a new item on each pass—is so common that Python provides a special shortcut for it.

The Dictionary Comprehension

A dictionary comprehension condenses the entire loop and dictionary creation process into a single, readable line inside curly braces {}.

The basic syntax is:

{key_expression: value_expression for item in iterable}

It reads a bit like an English sentence: “Create a new dictionary with this key_expression and value_expression for each item in this iterable.”

Let’s rewrite our squares example using a comprehension.

numbers = [1, 2, 3, 4]

# The same result, created in one line
squares_dict = {number: number ** 2 for number in numbers}

print(squares_dict)

This is not just shorter; it’s also often considered more declarative and “Pythonic.” It clearly states what you want the new dictionary to contain, rather than the step-by-step process of how to build it.

Another Example: Transforming an Existing Dictionary

Dictionary comprehensions are also great for creating a new dictionary based on the contents of an existing one. Let’s say we have a dictionary of prices in dollars and we want to create a new one with the prices in cents.

We can use the .items() method (from Post #67) right inside the comprehension.

prices_usd = {"apple": 0.50, "banana": 0.25, "orange": 0.60}

# Create a new dictionary by iterating over the old one's items
prices_cents = {item: price * 100 for (item, price) in prices_usd.items()}

print(prices_cents)

The output will be: {‘apple’: 50.0, ‘banana’: 25.0, ‘orange’: 60.0}.

Here, item and price are the temporary variables that hold the key and value from prices_usd.items() on each pass, just as they would in a standard for loop.

What’s Next?

Dictionary comprehensions are a powerful feature that you will encounter in more advanced Python code. While you don’t need to master them right away, seeing them now gives you a taste of the concise and expressive code you’ll be able to write in the future. We will revisit comprehensions in more detail later in the series.

We’ve spent a lot of time learning how to use dictionaries. But have you ever wondered why they are so prevalent in Python and other languages? What makes them so fast for looking up data? In Post #73, we will take a high-level look at the magic behind the scenes: hashing.

Author

Debjeet Bhowmik

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com

Leave a Comment