Python dictionary comprehension is one of the most powerful and elegant features in Python, letting you build dictionaries in a single, readable line of code. If you've used list comprehensions before, python dictionary comprehension follows the same pattern — but instead of producing a list, you get a fully formed dictionary. Whether you're learning to python create dict from list, python filter dict entries, or python transform dictionary values on the fly, mastering python dict comprehension syntax will make your code cleaner and faster. Let's break down everything you need to know.

What Is Python Dictionary Comprehension?

Python dictionary comprehension is a concise syntax for creating dictionaries from any iterable — lists, ranges, tuples, or even other dictionaries. Instead of writing a for loop with .update() or repeated assignments, you express the entire dictionary construction in one expression.

The basic python dict comprehension syntax looks like this:

{key_expression: value_expression for item in iterable}

Here's a quick example — creating a dictionary that maps each number to its square:

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

In just one line, python dictionary comprehension produces a complete dictionary. Without it, you'd need a for loop, a temporary variable, and multiple lines of code. The key and value expressions can be any valid Python expression, which makes this syntax incredibly flexible.

Python Dict Comprehension Syntax — Breaking It Down

Understanding the python dict comprehension syntax fully means knowing each part of the expression:

{key_expr: value_expr for var in iterable if condition}
  • key_expr — what each dictionary key will be
  • value_expr — what each dictionary value will be
  • for var in iterable — the loop that drives the comprehension
  • if condition — an optional filter (we'll cover this in depth below)

Here's a simple example mapping city names to their character length:

cities = ["Delhi", "Mumbai", "Kolkata", "Chennai"]
city_lengths = {city: len(city) for city in cities}
print(city_lengths)
# {'Delhi': 5, 'Mumbai': 6, 'Kolkata': 7, 'Chennai': 7}

The city variable plays double duty — it's the loop variable and also the key expression. The len(city) call computes the value. This is the heart of python dictionary comprehension: you define keys and values in terms of each element as you iterate.

Python Create Dict From List

One of the most common use cases for python dictionary comprehension is when you want to python create dict from list. You might have a list of items and need a dictionary where each item maps to some derived value.

Single List to Dictionary

fruits = ["apple", "banana", "cherry", "date"]
fruit_dict = {fruit: fruit.upper() for fruit in fruits}
print(fruit_dict)
# {'apple': 'APPLE', 'banana': 'BANANA', 'cherry': 'CHERRY', 'date': 'DATE'}

Here, python dictionary comprehension iterates over the fruits list. Each fruit becomes both the key (lowercase) and the value (uppercase). This is useful when you want quick lookup access to transformed versions of items.

Two Lists Into a Dictionary Using zip()

When you have two separate lists — one for keys and one for values — zip() pairs them up perfectly inside a python dict comprehension:

subjects = ["Math", "Science", "English", "History"]
scores = [88, 92, 75, 83]

report = {sub: score for sub, score in zip(subjects, scores)}
print(report)
# {'Math': 88, 'Science': 92, 'English': 75, 'History': 83}

The zip(subjects, scores) produces pairs like ("Math", 88), and the comprehension unpacks each pair into sub and score. This is one of the cleanest ways to python create dict from list using python dictionary comprehension.

Python Filter Dict — Conditional Dictionary Comprehension

The optional if clause in python dictionary comprehension lets you python filter dict entries based on any condition. Only items where the condition evaluates to True make it into the resulting dictionary.

Filtering by Value

inventory = {"apples": 30, "bananas": 5, "mangoes": 0, "grapes": 18, "kiwi": 2}

# Keep only items with stock above 10
in_stock = {item: qty for item, qty in inventory.items() if qty > 10}
print(in_stock)
# {'apples': 30, 'mangoes': 0 is excluded, 'grapes': 18}
# Actual output: {'apples': 30, 'grapes': 18}

The if qty > 10 condition acts as a gate — only dictionary entries where the quantity exceeds 10 pass through. This is how you python filter dict with python dictionary comprehension in a single readable expression.

Filtering by Key

You can filter based on the key too:

employee_ids = {"alice": 101, "bob": 202, "charlie": 303, "diana": 404}

# Keep only employees whose names start with a vowel
vowel_employees = {name: eid for name, eid in employee_ids.items() if name[0] in "aeiou"}
print(vowel_employees)
# {'alice': 101}

Here the filter checks the first character of each key. Python dictionary comprehension makes this kind of selective filtering both compact and self-documenting.

Python Conditional Dict Comprehension With if-else

Python conditional dict comprehension can also use an if-else expression inside the key or value part — this is different from filtering. When you use if-else in the value expression, every item is included, but the value changes based on the condition:

temperatures = {"Monday": 38, "Tuesday": 22, "Wednesday": 41, "Thursday": 19, "Friday": 35}

status = {day: "Hot" if temp > 30 else "Cool" for day, temp in temperatures.items()}
print(status)
# {'Monday': 'Hot', 'Tuesday': 'Cool', 'Wednesday': 'Hot', 'Thursday': 'Cool', 'Friday': 'Hot'}

Notice the placement: the if-else sits in the value position, not after the for. This is the key distinction in python conditional dict comprehension — if after for filters items out, while if-else in the expression transforms values but keeps all items.

Python Transform Dictionary — Modifying Keys and Values

A major use case for python dictionary comprehension is when you want to python transform dictionary data — change the keys, the values, or both — without mutating the original.

Transforming Values

prices_usd = {"laptop": 999, "mouse": 25, "keyboard": 75, "monitor": 450}
exchange_rate = 83.5

prices_inr = {item: round(price * exchange_rate, 2) for item, price in prices_usd.items()}
print(prices_inr)
# {'laptop': 83416.5, 'mouse': 2087.5, 'keyboard': 6262.5, 'monitor': 37575.0}

The original prices_usd dictionary is untouched. Python dictionary comprehension creates a brand new dictionary with transformed values.

Transforming Keys

You can rename or reformat keys just as easily:

raw_data = {"first_name": "Arjun", "last_name": "Sharma", "age": 29}

# Convert snake_case keys to camelCase
camel_data = {"".join(w.capitalize() if i else w for i, w in enumerate(k.split("_"))): v
              for k, v in raw_data.items()}
print(camel_data)
# {'firstName': 'Arjun', 'lastName': 'Sharma', 'age': 29}

This example uses a string expression to transform each key from snake_case to camelCase while keeping values unchanged. Python transform dictionary operations like this are cleaner in comprehension form than in imperative loops.

Swapping Keys and Values

Inverting a dictionary — making values into keys and keys into values — is trivial with python dictionary comprehension:

currency_codes = {"India": "INR", "USA": "USD", "UK": "GBP", "Japan": "JPY"}

inverted = {code: country for country, code in currency_codes.items()}
print(inverted)
# {'INR': 'India', 'USD': 'USA', 'GBP': 'UK', 'JPY': 'Japan'}

Just swap the positions of country and code in the key-value expression. This is one of the most elegant uses of python dict comprehension syntax.

Python Nested Dict Comprehension

Python nested dict comprehension refers to comprehensions where the output is a nested dictionary, or where the input itself is a nested structure. This is an advanced but practical technique.

Creating a Nested Dictionary

Suppose you want a multiplication table stored as a nested dictionary:

multiplication_table = {i: {j: i * j for j in range(1, 6)} for i in range(1, 4)}

for row, cols in multiplication_table.items():
    print(f"{row}: {cols}")
# 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}

The outer comprehension iterates over rows (i from 1 to 3), and the inner comprehension builds a sub-dictionary for each row. Python nested dict comprehension like this is extremely compact but can get hard to read if overused — a good rule of thumb is to stop at two levels of nesting.

Flattening a Nested Dictionary

You can also use python nested dict comprehension to flatten a nested structure into a single-level dictionary:

department_scores = {
    "Engineering": {"Alice": 91, "Bob": 85},
    "Marketing": {"Carol": 78, "Dave": 88}
}

flat_scores = {name: score for dept, members in department_scores.items()
               for name, score in members.items()}
print(flat_scores)
# {'Alice': 91, 'Bob': 85, 'Carol': 78, 'Dave': 88}

Two for clauses in the same comprehension let you iterate over the outer dictionary and then the inner one. This is one of the most powerful patterns in python dictionary comprehension for working with nested data.

Dictionary Comprehension vs. dict() Constructor

Python gives you another way to create dictionaries from iterables — the built-in dict() constructor. When should you use python dictionary comprehension vs. dict()?

# Using dict() with zip — clean for simple cases
names = ["tiger", "elephant", "panda"]
weights_kg = [220, 4500, 100]
animals = dict(zip(names, weights_kg))
print(animals)
# {'tiger': 220, 'elephant': 4500, 'panda': 100}

# Python dictionary comprehension — better when transformation or filtering is needed
heavy_animals = {name: wt for name, wt in zip(names, weights_kg) if wt > 200}
print(heavy_animals)
# {'tiger': 220, 'elephant': 4500}

Use dict() for straightforward key-value pairing from two iterables. Use python dictionary comprehension whenever you need conditional logic, value transformation, or any expression more complex than a direct mapping.

Full Working Example

Here's a comprehensive example that ties together python dictionary comprehension, python filter dict, python conditional dict comprehension, and python transform dictionary — all in one realistic scenario.

# Full example: Student grade processing with Python Dictionary Comprehension

students_raw = [
    {"name": "Priya", "marks": 91, "subject": "Physics"},
    {"name": "Rahul", "marks": 47, "subject": "Chemistry"},
    {"name": "Sneha", "marks": 73, "subject": "Math"},
    {"name": "Arjun", "marks": 58, "subject": "Biology"},
    {"name": "Meera", "marks": 85, "subject": "Physics"},
    {"name": "Kiran", "marks": 33, "subject": "Math"},
]

# 1. Python create dict from list — map student name to marks
name_to_marks = {s["name"]: s["marks"] for s in students_raw}
print("Name to Marks:")
print(name_to_marks)
# {'Priya': 91, 'Rahul': 47, 'Sneha': 73, 'Arjun': 58, 'Meera': 85, 'Kiran': 33}

# 2. Python filter dict — keep only students who passed (marks >= 50)
passed_students = {name: marks for name, marks in name_to_marks.items() if marks >= 50}
print("\nPassed Students:")
print(passed_students)
# {'Priya': 91, 'Sneha': 73, 'Arjun': 58, 'Meera': 85}

# 3. Python conditional dict comprehension — assign letter grades
grade_map = {
    name: "A" if marks >= 80 else "B" if marks >= 60 else "C" if marks >= 50 else "F"
    for name, marks in name_to_marks.items()
}
print("\nGrade Map:")
print(grade_map)
# {'Priya': 'A', 'Rahul': 'F', 'Sneha': 'B', 'Arjun': 'C', 'Meera': 'A', 'Kiran': 'F'}

# 4. Python transform dictionary — normalize marks to percentage out of 100
# (Already out of 100 here, so let's scale to GPA out of 4.0)
gpa_dict = {name: round((marks / 100) * 4.0, 2) for name, marks in name_to_marks.items()}
print("\nGPA (out of 4.0):")
print(gpa_dict)
# {'Priya': 3.64, 'Rahul': 1.88, 'Sneha': 2.92, 'Arjun': 2.32, 'Meera': 3.4, 'Kiran': 1.32}

# 5. Python nested dict comprehension — build a subject-wise dict of passing students
subjects = list({s["subject"] for s in students_raw})
subject_wise = {
    subject: {s["name"]: s["marks"] for s in students_raw if s["subject"] == subject and s["marks"] >= 50}
    for subject in subjects
}
print("\nSubject-wise Passed Students:")
for sub, data in subject_wise.items():
    print(f"  {sub}: {data}")
# Physics: {'Priya': 91, 'Meera': 85}
# Chemistry: {}
# Math: {'Sneha': 73}
# Biology: {'Arjun': 58}

Expected Output:

Name to Marks:
{'Priya': 91, 'Rahul': 47, 'Sneha': 73, 'Arjun': 58, 'Meera': 85, 'Kiran': 33}

Passed Students:
{'Priya': 91, 'Sneha': 73, 'Arjun': 58, 'Meera': 85}

Grade Map:
{'Priya': 'A', 'Rahul': 'F', 'Sneha': 'B', 'Arjun': 'C', 'Meera': 'A', 'Kiran': 'F'}

GPA (out of 4.0):
{'Priya': 3.64, 'Rahul': 1.88, 'Sneha': 2.92, 'Arjun': 2.32, 'Meera': 3.4, 'Kiran': 1.32}

Subject-wise Passed Students:
  Physics: {'Priya': 91, 'Meera': 85}
  Chemistry: {}
  Math: {'Sneha': 73}
  Biology: {'Arjun': 58}

This example demonstrates everything covered in this guide — all built on python dictionary comprehension. For more on Python's built-in data structures, check out the official Python documentation on dictionaries.


Ready to go deeper? This guide is part of a complete Python tutorial series covering everything from basics to advanced topics. Whether you're just starting out or looking to sharpen your skills, the full series has you covered. Learn the full Python tutorial here.