Python dictionary comprehension [7 methods]

In this Python tutorial, I will explain what is Python dictionary comprehension. We will also explore the various methods of Python dictionary comprehension with the help of some scenario-based examples and how Python dict comprehension is different from list comprehension.

Python is known for its succinct and readable code, and one of the features that contribute to this reputation is dictionary comprehension. This feature allows developers to create Python dictionaries concisely and expressively, which can be particularly useful in scenarios where a Python dictionary is being generated from data.

What is a Dictionary Comprehension Python

At its core, Python dictionary comprehension (often termed dict comprehension) is a method to transform one Python dictionary (or any iterable) into another dictionary using a single line of code.

During this transformation, items within the source can be conditionally included in the new Python dictionary and each item can be transformed as needed.

Methods for Python Dict Comprehension

There are seven different ways in Python for dict comprehension:

  • Basic dictionary comprehension
  • dict comprehension with multiple keys
  • Python dict comprehension if else
  • defaultdict comprehension
  • dictionary comprehension lists
  • dict comprehension swap keys and values
  • Dictionary comprehension with another dict

Let’s see them one by one using illustrative examples:

Method 1: Basic Dict Comprehension Python

This method allows for the swift creation of a Python dictionary by iterating over an iterable (typically a list of tuples). Each tuple’s items are directly mapped to key-value pairs in the resultant Python dictionary.

The basic syntax of dict comprehension Python is:

{key_expr: value_expr for item in iterable}

Where:

  • key_expr: is the expression that determines the key for each Python dictionary entry.
  • value_expr: is the expression that provides the value corresponding to each key.
  • iterable: any Python object that can be looped over (like a list, tuple, set, etc.).

Scenario: Let’s consider we have a Python list of US Presidents and their respective years of birth. We’ll use Python dictionary comprehension to convert this list into a Python dictionary.

presidents_birth_years = [('George Washington', 1732), ('Thomas Jefferson', 1743), ('Abraham Lincoln', 1809)]
presidents_dict = {president: year for president, year in presidents_birth_years}
print(presidents_dict)

The output is: In this example, the list of tuples is iterated over, and each tuple’s items (president and year) are mapped directly to key-value pairs in the resultant Python dictionary.

{'George Washington': 1732, 'Thomas Jefferson': 1743, 'Abraham Lincoln': 1809}
dict comprehension python

This way we can use basic dictionary comprehension in Python to create a Dictionary.

Method 2: Python Dictionary Comprehension with Multiple Keys

Sometimes, we need a dictionary comprehension with multiple keys. Here, Python dictionary comprehension is used with multiple loops, which allows for the creation of a dictionary in Python where each key might correspond to multiple values, often organized as lists.

Scenario: Suppose we have a list of famous landmarks and their respective states. We wish to create a dictionary in Python, where each state is paired with a list of its landmarks.

landmarks = [('Statue of Liberty', 'New York'), ('Mount Rushmore', 'South Dakota'), ('Hollywood Sign', 'California')]
landmark_dict = {state: [landmark for landmark, s in landmarks if s == state] for landmark, state in landmarks}
print(landmark_dict)

The output is: Here, the dictionary comprehension multiple keys have multiple loops to first generate a list of landmarks for each state and then map them to their respective states.

{'New York': ['Statue of Liberty'], 'South Dakota': ['Mount Rushmore'], 'California': ['Hollywood Sign']}
python dictionary comprehension multiple keys

This way we use Python dict comprehension of multiple keys to create a dictionary.

Method 3: Python dictionary comprehension if else

We can also incorporate if-else conditions in our dict comprehension in Python. It can serve two purposes: filtering out items based on a condition, and modifying items’ values based on the condition.

Scenario: We have a Python dict of US states and their total land area. We want to categorize states as ‘Large’ if their area is more than 100,000 sq. miles, and ‘Small’ otherwise, using dict comprehension if else.

state_area = {'California': 163696, 'Rhode Island': 1034, 'Texas': 268596}
area_category = {state: 'Large' if area > 100000 else 'Small' for state, area in state_area.items()}
print(area_category)

The output is: The Python dict comprehension checks the area of each state and assigns a category based on the provided if else conditions.

{'California': 'Large', 'Rhode Island': 'Small', 'Texas': 'Large'}
dictionary comprehension python if else

This way we can have dict comprehension if else to create Python dict.

Method 4: Python defaultdict comprehension

While not a native feature in Python, we can emulate defaultdict comprehension by combining defaultdict from the collections module with dict comprehension in Python. This is especially useful when we want to automatically initialize Python dictionary keys with default values, such as empty lists.

Scenario: Let’s categorize US cities by their starting letter using the combination of defaultdict and dict comprehension, emulating Python defaultdict comprehension.

from collections import defaultdict
us_cities = ['Denver', 'Detroit', 'Dallas', 'Boston', 'Baltimore']
city_dict_default = defaultdict(list)
{city_dict_default[city[0]].append(city) for city in us_cities}
print(dict(city_dict_default))

The output is: Cities are grouped by their starting letters using defaultdict and dictionary comprehension in Python

{'D': ['Denver', 'Detroit', 'Dallas'], 'B': ['Boston', 'Baltimore']}
Python dictionary comprehension

This way we can use the defaultdict for dict comprehension in Python.

Method 5: Python dict comprehension with two lists

Case 1: This involves creating a dictionary using two lists: one list as the keys and the other as the values. The zip() function is typically used to combine the two lists.

Scenario: Suppose we have two lists – one of US states and the other of their corresponding capitals. We want to combine them into a dictionary where states are the keys and capitals are the values.

sports = ['baseball', 'basketball', 'football']
balls = ['baseball', 'basketball', 'football']

sports_ball_dict = {sport: ball for sport, ball in zip(sports, balls)}
print(sports_ball_dict)

The output is:

{'baseball': 'baseball', 'basketball': 'basketball', 'football': 'football'}
dict comprehension in Python

This way we can use the zip() function for Python dict comprehension with two lists.

Case 2: We can also use general dict comprehension with range function in Python

Suppose we have two Python lists – one of US states and the other of their corresponding capitals. We want to combine them into a Python dictionary where states are the keys and capitals are the values.

states = ["California", "Texas", "New York"]
capitals = ["Sacramento", "Austin", "Albany"]

state_capital = {states[i]: capitals[i] for i in range(len(states))}
print(state_capital)

The output is:

{'California': 'Sacramento', 'Texas': 'Austin', 'New York': 'Albany'}
Python dict comprehension

This way we can use the range function within dict comp in Python.

Method 6: Python Dict comprehension swapping keys and values

Sometimes we might want to reverse the roles of keys and values in a dictionary. This method shows how to do that using Python dictionary comprehension.

Scenario: Let’s consider a Python dictionary containing major US car manufacturers and their headquarters.

car_manufacturer_location = {
    'Ford': 'Dearborn',
    'Tesla': 'Palo Alto',
    'Chevrolet': 'Detroit'
}
swapped_dict = {location: manufacturer for manufacturer, location in car_manufacturer_location.items()}
print(swapped_dict)

The output is:

{'Dearborn': 'Ford', 'Palo Alto': 'Tesla', 'Detroit': 'Chevrolet'}
Python comprehension dictionary

This way we can use Python dictionary comprehension for key value swapping.

Method 7: Python Dictionary comprehension from another dictionary

This involves creating a new dictionary in Python based on an existing one by applying some operations or filtering.

Case 1: Let’s consider a scenario where we have a Python dictionary of average monthly temperatures in Fahrenheit for various US cities, and we want a dictionary with only those cities where the average temperature is above 70F.

avg_temps = {
    'Miami': 78,
    'Seattle': 60,
    'Los Angeles': 72,
    'Chicago': 65
}
warm_cities = {city: temp for city, temp in avg_temps.items() if temp > 70}
print(warm_cities)

Output:

{'Miami': 78, 'Los Angeles': 72}
filtering dict with Python dict comprehension

This way we can filter a dict and create a new dict with that using dict comprehension in Python.

Case 2: This involves performing some arithmetic operations on the values (or keys) from an existing Python dictionary to create a new one.

Scenario: Imagine we’re studying the average consumption of soft drinks in liters in different US states, but the data we have is in gallons. We decided to convert these values from gallons to liters (1 gallon is approximately 3.78541 liters).

consumption_gallons = {
    'California': 20,
    'Texas': 15,
    'Florida': 18
}
consumption_liters = {state: gallons * 3.78541 for state, gallons in consumption_gallons.items()}
print(consumption_liters)

Output:

{'California': 75.7082, 'Texas': 56.781150000000004, 'Florida': 68.13738000000001}
Dictionary comp in Python with dict

This way we can perform arithmetic operations on a dictionary and get a new Python dictionary using dictionary comprehension in Python.

Comparing Dict Comprehension and List Comprehension in Python

This highlights the difference between list comprehension (which generates lists) and dictionary comprehension (which produces dictionaries). Both are syntactic tools in Python that allow for concise iteration and transformation of iterables.

Scenario for List Comprehension: Using list comprehension in Python, let’s create a list of lengths of names of some US lakes.

lakes = ['Lake Tahoe', 'Lake Superior', 'Lake Erie']
lake_lengths = [len(lake) for lake in lakes]
print(lake_lengths)

The output is:

[10, 13, 9]
list comprehension python dictionary

This way we can create a list from list comprehension in Python.

For Dict Comprehension: Use the same list of the US lakes.

lakes = ['Lake Tahoe', 'Lake Superior', 'Lake Erie']
lake_length_dict = {lake: len(lake) for lake in lakes}
print(lake_length_dict)

The output is:

{'Lake Tahoe': 10, 'Lake Superior': 13, 'Lake Erie': 9}
dictionary comprehension python

This way we can create a Python dictionary using dict comprehension.

Conclusion

This tutorial explains what is Python dictionary comprehension with four different methods such as basic dict comprehension, multiple keys, if-else conditions, with another dict, swap keys and values, with two lists, or defaultdict comprehension with demonstrative examples. Also, we have compared list comprehension with dict comprehension.

In Python Dictionary comprehension offers a clear and concise way to generate dictionaries. Whether we’re working with single keys, multiple keys, or conditional statements, Python’s expressive syntax allows for powerful and readable data transformations.

You may also like to read: