Python Dictionary Comprehension: A Fast and Flexible Way to Build Dictionaries

Introduction

Dictionaries are a very powerful, Pythonic way to store data. They allow us to associate a key with a value, and access them as needed. This makes it easy to store data where, for example, we need to associate a string with a number. For instance, if we need to store data related to names and associated phone numbers, then the dictionary is the best data structure to do so.

In this article, we'll show what a dictionary is and discuss how to use the dictionary comprehension methodology to create dictionaries in a Pythonic and elegant way. In particular, creating dictionaries with comprehension is useful in situations when we have to retrieve data from other data structures to store them in a dictionary.

What are dictionaries?

A dictionary is a Pythonic way to store data that is coupled as keys and values. Here is an example of how we can create one:

my_dictionary = {'key_1':'value_1', 'key_2':'value_2'}

One of the powerful aspects of dictionaries is the fact that we have no particular limitations on the type of values we can store in them.

For example, we can store strings as well as integers or floats, and even lists or tuples. But we can also create nested dictionaries, meaning: store dictionaries inside of a dictionary.

Let's see some examples.

Suppose we want to associate the names and the surnames of some people. We can use a dictionary to store string values,
like so:

names = {'Doe': 'John', 'Bush': 'Simon', 'Johnson': 'Elizabeth'}

Then, if we want to see the result, we can just print it:

print(names)

and we get:

{'Doe': 'John', 'Bush': 'Simon', 'Johnson': 'Elizabeth'}

Instead, suppose we want to store the names of some people and their ages. We can store the age as int values, like so:

ages = {'James': 15, 'Susan': 27, 'Tricia': 32}

And, again, to see the results:

print(ages)
# {'James': 15, 'Susan': 27, 'Tricia': 32}

Now, suppose we need to write down a shopping list. We can store the items to buy either as a list or tuple in the values of our dictionary. For example, let's use a list:

# Create dictionary
shopping_list = {'fruit': ['apple', 'banana', 'orange'], 'vegetables': ['broccoli', 'salad']}

# Print dictionary
print(shopping_list)

And we get:

{'fruit': ['apple', 'banana', 'orange'], 'vegetables': ['broccoli', 'salad']}

Finally, suppose we want to store some data related to a classroom. In particular, suppose we want to know the names, ages, and grades of some students in a classroom. We can store this data as a nested dictionary like so:

# Create nested dictionary
classroom = {
    'student_1': {
        'name': 'Alice',
        'age': 15,
        'grades': [90, 85, 92]
    },
    'student_2': {
        'name': 'Bob',
        'age': 16,
        'grades': [80, 75, 88]
    },
    'student_3': {
        'name': 'Charlie',
        'age': 14,
        'grades': [95, 92, 98]
    }
}

# Print the nested dictionary
print(classroom)

and we get:

{'student_1': {'name': 'Alice', 'age': 15, 'grades': [90, 85, 92]}, 'student_2': {'name': 'Bob', 'age': 16, 'grades': [80, 75, 88]}, 'student_3': {'name': 'Charlie', 'age': 14, 'grades': [95, 92, 98]}}

Now, while we may need to write dictionaries "by hand" as we did here, the reality is that in most programming applications, we need to create dictionaries by retrieving data from different sources, and this is where dictionary comprehension comes in handy.

What is dictionary comprehension?

Dictionary comprehension is a useful feature in Python that allows us to create dictionaries concisely and efficiently. It's a powerful tool that can save us time and effort, especially when working with large amounts of data.

It's similar to list comprehension but, instead of creating a list, it creates a dictionary. The syntax is as follows:

{key: value for (key, value) in iterable}

In the above syntax, key and value are the keys and values that we want to include in the dictionary, respectively. iterable, on the other hand, is any iterable object, such as a list, or a tuple that contains the values that we want to use as keys and values in the dictionary.

So, let's explore the iterables we can use with some practical examples.

Example Use-Cases

Let's examine some practical examples to demonstrate how dictionary comprehension works in different usage scenarios.

Transforming Dictionary Values

The first example we want to showcase is how to use dictionary comprehension to transform the values of a dictionary. For instance, consider we have the following dictionary:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

# Create dictionary
original_dict = {'a': '1', 'b': '2', 'c': '3'}

In this example, both the keys and the values are str. Now, suppose we want to convert the type of the numbers to int. We can use dictionary comprehension like so:

# Transform and print
transformed_dict = {key: int(value) for key, value in original_dict.items()}

print(transformed_dict)

So, the output of our transformed dictionary is:

{'a': 1, 'b': 2, 'c': 3}

Filtering with if, if-else Statements, and for Loops

Suppose we have a dictionary reporting the prices of various fruits, and we want to filter the fruits with prices lower than a certain threshold. Here's how we can use dictionary comprehension to accomplish this:

# Define initial dictionary
products = {'apple': 1.0, 'banana': 0.5, 'orange': 1.5, 'pear': 0.75}

# Define threshold
max_price = 0.75

# Filter for threshold
cheap_products = {fruit: price for fruit, price in products.items() if price <= max_price}

# Print filtered dictionary
print(cheap_products)

And we have:

{'banana': 0.5, 'pear': 0.75}

So, we've easily excluded the apple and orange as they cost more than our threshold.

Now, let's see another example where we filter our data, but in this case, we want to use the else statement. For example, consider we have a dictionary reporting some fruits and their prices. We want to create a new dictionary where prices higher than 10 are discounted by 10%. Here's how we can do so:

# Define initial dictionary
products = {'apple': 1.0, 'banana': 5.0, 'orange': 15.0, 'pear': 10.0}

# Create new dictionary
discounted_products = {fruit: price * 0.9 if price > 10 else price for fruit, price in products.items()}

# Print results
print(discounted_products)

And we get:

{'apple': 1.0, 'banana': 5.0, 'orange': 13.5, 'pear': 10.0}

So, we have applied a 10% discount to the price of the orange (the only one with a price higher than 10).

But we can do more. Suppose, for example, that we've stored some fruits with their prices again. We want to extract the name of a particular fruit and its price. For instance, imagine I love apples; so I want to know how much they cost. This is what we could do:

# Define dictionary
products = {'apple': 1.0, 'banana': 0.5, 'orange': 1.5, 'pear': 0.75}

# Choose one fruit
my_fruit = 'apple'

# Create new dictionary
my_product = {fruit: price for fruit, price in products.items() if fruit == my_fruit}

Now we can iterate over the new dictionary:

for fruit, price in my_product.items():
    print(f"My favorite fruit is {fruit} and it costs {price}")

And we get:

My favorite fruit is apple and it costs 1.0

Creating Lookup Tables

A lookup table is an array that maps input with output values. So, it somehow approximates a mathematical function.

Suppose we have two dictionaries: one mapping names to emails and the other mapping names to mobile phone numbers. We want to create a lookup table that maps the names to the phone numbers. We can do it like so:

# First dictionary
names_to_emails = {'Alice': '[email protected]', 'Bob': '[email protected]', 'Charlie': '[email protected]'}

# Second dictionary
emails_to_phones = {'[email protected]': '555-1234', '[email protected]': '555-5678', '[email protected]': '555-9012'}

# Create new lookup table
names_to_phones = {name: emails_to_phones[email] for name, email in names_to_emails.items()}

# Print new lookup table
print(names_to_phones)

And we get:

{'Alice': '555-1234', 'Bob': '555-5678', 'Charlie': '555-9012'}

Creating Dictionaries from Pandas DataFrames

We can use dictionary comprehension to create dictionaries by retrieving data from Pandas data frames. For example, consider we have a data frame containing columns with names, ages, countries, and salaries of some people. We can create a dictionary with names and ages like so:

# Create data frame
import pandas as pd

df = pd.DataFrame({
    'Name': ['John', 'Jane', 'Bob', 'Alice'],
    'Age': [25, 30, 42, 35],
    'Country': ['USA', 'Canada', 'Australia', 'UK'],
    'Salary': [50000, 60000, 70000, 80000]
})

# Get name and age
name_age_dict = {name: age for name, age in zip(df['Name'], df['Age'])}

# Print dictionary
print(name_age_dict)

And we get:

{'John': 25, 'Jane': 30, 'Bob': 42, 'Alice': 35}

Creating Dictionaries from Lists and Tuples

We can use dictionary comprehension to create dictionaries by retrieving data from lists and tuples. For example, if we want to retrieve some data from two lists, we can write the following code:

# Define names and ages in lists
names = ['John', 'Jane', 'Bob', 'Alice']
ages = [25, 30, 42, 35]

# Create dictionary from lists and print results
name_age_dict = {name: age for name, age in zip(names, ages)}
print(name_age_dict)

And we get:

{'John': 25, 'Jane': 30, 'Bob': 42, 'Alice': 35}

Note: The code would be the same in case we'd use tuples rather than lists.

Conclusions

In this article, we've seen how dictionary comprehension can help us in a variety of practical situations, making it easy to create new dictionaries by retrieving data from different sources. The brevity of comprehension makes creating dictionaries a simple and fast process.

Last Updated: June 7th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Federico TrottaAuthor

I'm a Mechanical Engineer who's worked in the industrial field for 5 years.

Thanks to my curiosity, I discovered programming and AI. Having a burning passion for writing, I couldn't avoid starting to write about these topics, so I decided to change my career to become a Technical Writer.

My purpose is to educate people on Python programming, Machine Learning, and Data Science, through writing.

Want to contact me? Here are my contacts: https://bio.link/federicotrotta

Ā© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms