Skip to main content

Python Dictionary Comprehension

Dictionary comprehensions are an elegant way to create or transform dictionaries in Python. Similar to list comprehensions, they provide a concise syntax for creating dictionaries in a single line of code, making your Python code more readable and Pythonic.

Introduction to Dictionary Comprehensions

Dictionary comprehension was introduced in Python 2.7 and provides a shorter syntax when you want to create a new dictionary based on the values of an existing iterable or to transform an existing dictionary.

The basic syntax of a dictionary comprehension is:

python
{key_expression: value_expression for item in iterable}

Where:

  • key_expression is the expression that will become the key in the new dictionary
  • value_expression is the expression that will become the value in the new dictionary
  • item is the variable that takes each value in the iterable

Basic Dictionary Comprehension Examples

Example 1: Creating a dictionary from a list

Let's create a dictionary where the keys are numbers from 1 to 5 and values are their squares:

python
# Using dictionary comprehension
squares = {x: x*x for x in range(1, 6)}
print(squares)

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

The same result using a traditional for loop would look like:

python
# Using traditional for loop
squares = {}
for x in range(1, 6):
squares[x] = x*x
print(squares)

Example 2: Creating a dictionary from two lists

You can use zip() with dictionary comprehension to create a dictionary from two lists:

python
fruits = ['apple', 'banana', 'cherry', 'date']
prices = [1.2, 0.5, 2.5, 3.0]

fruit_prices = {fruit: price for fruit, price in zip(fruits, prices)}
print(fruit_prices)

Output:

{'apple': 1.2, 'banana': 0.5, 'cherry': 2.5, 'date': 3.0}

Conditional Dictionary Comprehensions

You can add conditions to dictionary comprehensions to filter items:

Example 3: Filtering with if condition

Let's create a dictionary of even squares:

python
even_squares = {x: x*x for x in range(1, 11) if x % 2 == 0}
print(even_squares)

Output:

{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

Example 4: Using if-else in dictionary comprehension

You can use the conditional expression (ternary operator) for more complex logic:

python
numbers = range(1, 11)
number_category = {num: "even" if num % 2 == 0 else "odd" for num in numbers}
print(number_category)

Output:

{1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd', 6: 'even', 7: 'odd', 8: 'even', 9: 'odd', 10: 'even'}

Nested Dictionary Comprehensions

You can also create nested dictionaries using comprehensions:

python
nested_dict = {outer: {inner: inner * outer for inner in range(1, 6)} for outer in range(1, 4)}
print(nested_dict)

Output:

{1: {1: 1, 2: 2, 3: 3, 4: 4, 5: 5}, 2: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}, 3: {1: 3, 2: 6, 3: 9, 4: 12, 5: 15}}

Practical Applications

Example 5: Converting temperature from Celsius to Fahrenheit

Let's convert a dictionary of city temperatures from Celsius to Fahrenheit:

python
celsius_temps = {
'New York': 21,
'London': 18,
'Paris': 23,
'Tokyo': 27,
'Sydney': 32
}

# Convert to Fahrenheit: F = C * 9/5 + 32
fahrenheit_temps = {city: temp * 9/5 + 32 for city, temp in celsius_temps.items()}
print(fahrenheit_temps)

Output:

{'New York': 69.8, 'London': 64.4, 'Paris': 73.4, 'Tokyo': 80.6, 'Sydney': 89.6}

Example 6: Counting word frequency in a text

python
text = "the quick brown fox jumps over the lazy dog"
word_count = {word: text.split().count(word) for word in set(text.split())}
print(word_count)

Output:

{'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1}

Example 7: Data transformation for a web application

Let's transform user data for a web application:

python
users = [
{'id': 1, 'name': 'Alice', 'active': True},
{'id': 2, 'name': 'Bob', 'active': False},
{'id': 3, 'name': 'Charlie', 'active': True},
]

# Create a dictionary with id as key and user data as value
user_lookup = {user['id']: user for user in users}
print(user_lookup)

# Or get only active users
active_users = {user['id']: user['name'] for user in users if user['active']}
print(active_users)

Output:

{1: {'id': 1, 'name': 'Alice', 'active': True}, 2: {'id': 2, 'name': 'Bob', 'active': False}, 3: {'id': 3, 'name': 'Charlie', 'active': True}}
{1: 'Alice', 3: 'Charlie'}

Performance Considerations

Dictionary comprehensions are not only more concise but can also be more efficient than traditional for loops for creating dictionaries. However, there are a few things to keep in mind:

  1. If the dictionary comprehension becomes too complex, it might harm readability
  2. For very large data sets, memory usage might be a concern
  3. If you need to perform multiple operations on each item, sometimes a regular for loop might be clearer

Common Mistakes and How to Avoid Them

Mistake 1: Overwriting existing keys

If your key expression generates duplicate keys, later values will overwrite earlier ones:

python
words = ["apple", "banana", "apricot", "cherry"]
first_letter_word = {word[0]: word for word in words}
print(first_letter_word)

Output:

{'a': 'apricot', 'b': 'banana', 'c': 'cherry'}

Notice that 'apricot' overwrote 'apple' because they both start with 'a'.

Mistake 2: Complex expressions reducing readability

Avoid writing overly complex dictionary comprehensions:

python
# Avoid this - too complex
data = {k: v for k, v in ((str(i), i * i) for i in range(1, 6) if i % 2 == 0)}

# Better approach - split it up
even_numbers = [i for i in range(1, 6) if i % 2 == 0]
data = {str(i): i * i for i in even_numbers}
print(data)

Output:

{'2': 4, '4': 16}

Summary

Dictionary comprehensions are a powerful feature in Python that allow you to:

  1. Create dictionaries concisely in a single line
  2. Transform existing dictionaries
  3. Filter dictionary items based on conditions
  4. Make your code more readable and Pythonic

When used appropriately, dictionary comprehensions can significantly reduce the amount of code you write while making it more expressive and easier to understand.

Practice Exercises

  1. Create a dictionary mapping numbers 1-10 to their cubes using dictionary comprehension.
  2. Given a string, create a dictionary that maps each character to its ASCII value.
  3. Convert a dictionary with string values to a dictionary where all values are uppercase.
  4. Create a dictionary that maps each word in a sentence to its length, but only for words longer than 3 characters.
  5. Given a dictionary of student scores, create a new dictionary that includes only students who passed (score >= 60).

Additional Resources

Dictionary comprehensions, along with list and set comprehensions, are one of Python's most elegant features. Mastering them will significantly improve your Python coding style and efficiency.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)