Python Dictionary Comprehension: Create a Dictionary in One Line of Code

  • Home
  • Python Dictionary Comprehension: Create a Dictionary in One Line of Code

Dictionary Comprehension – Creating a Dictionary in One Line of Code

In Python, Dictionary Comprehension is a concise, expressive, and distinctly “Pythonic” syntax that lets you build a new dictionary from any iterable (such as a list, tuple, range, or an existing dictionary) in a single line of code.

If you are already comfortable with list comprehensions, you will pick up dictionary comprehensions in just a few minutes.

1. Basic Syntax

The standard syntax for a dictionary comprehension looks like this:

Python

new_dict = {key_expr: value_expr for item in iterable}
  • key_expr: An expression that produces the key for each item.

  • value_expr: An expression that produces the value corresponding to that key.

  • item in iterable: A loop iterating over the source collection.

Example 1: Create a dictionary of squares from a range

Python

squares = {x: x**2 for x in range(1, 6)}
print(squares)
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Compared to the traditional for loop approach:

Python

squares = {}
for x in range(1, 6):
    squares[x] = x**2

Dictionary comprehension keeps your code more compact, reduces temporary variables, and reads cleanly once you get used to the pattern.

2. Adding a Filter Condition (if)

You can append an if clause at the end to include only items that satisfy a condition:

Python

new_dict = {key_expr: value_expr for item in iterable if condition}

Example 2: Cube only even numbers

Python

even_cubes = {x: x**3 for x in range(1, 11) if x % 2 == 0}
print(even_cubes)
# Output: {2: 8, 4: 64, 6: 216, 8: 512, 10: 1000}

3. Conditional Branching (if - else) in the Value Expression

Unlike a filter at the end, if you want to transform values conditionally (if ... else ...), place the conditional expression before the for keyword:

Python

scores = {"Alice": 85, "Bob": 42, "Charlie": 90, "David": 50}
status = {name: ("Pass" if score >= 50 else "Fail") for name, score in scores.items()}
print(status)
# Output: {'Alice': 'Pass', 'Bob': 'Fail', 'Charlie': 'Pass', 'David': 'Pass'}

4. Practical Use Cases

Pair two lists into a dictionary with zip()

Python

keys = ["name", "role", "stack"]
values = ["Minh", "Backend Dev", "Python"]

profile = {k: v for k, v in zip(keys, values)}
print(profile)
# Output: {'name': 'Minh', 'role': 'Backend Dev', 'stack': 'Python'}

(Tip: If you don’t need to transform k or v, you can call dict(zip(keys, values)) directly.)

Swap keys and values in an existing dictionary

Python

http_codes = {"OK": 200, "Not Found": 404, "Server Error": 500}
code_to_msg = {v: k for k, v in http_codes.items()}
print(code_to_msg)
# Output: {200: 'OK', 404: 'Not Found', 500: 'Server Error'}

Normalize keys or values (e.g., lowercase and trim whitespace)

Python

raw_prices = {" Apple ": 2.5, "BANANA": 1.5, " Orange": 3.0}
clean_prices = {fruit.strip().lower(): price for fruit, price in raw_prices.items()}
print(clean_prices)
# Output: {'apple': 2.5, 'banana': 1.5, 'orange': 3.0}

Filter an existing dictionary by key or value

Python

inventory = {"keyboard": 12, "mouse": 0, "monitor": 5, "cable": 0}
in_stock = {item: qty for item, qty in inventory.items() if qty > 0}
print(in_stock)
# Output: {'keyboard': 12, 'monitor': 5}

5. Important Things to Keep in Mind

  1. Duplicate keys overwrite earlier values: If your key expression produces the same key more than once, later entries overwrite earlier ones.

  2. Don’t overcomplicate a single line: Concise code is only good when it remains readable. If you need nested loops or complex conditions that make the line hard to follow, use a standard for loop or a helper function instead.

  3. Keys must be hashable: Dictionary keys must be immutable and hashable types such as int, str, or tuple (containing hashable elements). Using a list or dict as a key raises a TypeError: unhashable type.

Summary

Dictionary comprehension is a handy tool for transforming, filtering, and mapping key-value data cleanly in Python. Use it whenever it makes your intent clearer, and reach for explicit loops when logic grows complex.

Categories:

Leave Comment

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30