Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python Dictionary: Comprehension

Python Dictionary Comprehension - Complete Guide

Learn how to create dictionaries concisely and efficiently using dictionary comprehension.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • What is Dictionary Comprehension?
  • Basic Syntax
  • Filtering with if
  • if-else in Expression
  • Nested Dictionary Comprehension
  • Multiple Conditions
  • Swapping Keys and Values
  • Common Mistakes
  • Try It Yourself
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • Basic syntax — how dictionary comprehension works
  • Filtering — using if to pick certain items
  • if-else — deciding values based on conditions
  • Nested comprehension — working with nested loops
  • Swapping — flipping keys and values
  • Common mistakes — and how to avoid them

What is Dictionary Comprehension?

Dictionary comprehension is a neat way to create dictionaries in Python. Instead of writing a loop with several lines of code, you can do it all in one line. It's like a shortcut that makes your code shorter and often easier to read.

Think of it this way: you have some data, you want to transform it into a dictionary, and you want to do it quickly. Dictionary comprehension does exactly that.

Here's the basic structure:

{key: value for item in iterable if condition}

Let's break that down:

  • key — what you want as the key
  • value — what you want as the value
  • item — each element from your source
  • iterable — where the data comes from (list, range, etc.)
  • if condition — optional, filters which items to include

💡 Here's the thing: Dictionary comprehension is great for simple transformations. If your logic gets too complicated, a regular loop might be easier to understand.

Basic Syntax

1

Your First Dictionary Comprehension

Let's start with something simple. Say you have a list of numbers and you want a dictionary where each number is the key and its square is the value.

# Traditional way (using a loop)
numbers = [1, 2, 3, 4, 5]
squares = {}
for num in numbers:
    squares[num] = num ** 2
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# With dictionary comprehension (much shorter!)
squares = {num: num ** 2 for num in numbers}
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

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

# With strings
words = ["apple", "banana", "cherry"]
word_lengths = {word: len(word) for word in words}
print(word_lengths)  # {'apple': 5, 'banana': 6, 'cherry': 6}

What's happening here:

  • We go through each item in the list
  • We create a key-value pair for each item
  • The result is a brand new dictionary
  • The original list stays unchanged

Quick Check: What does dictionary comprehension return? (Answer: A new dictionary)

Filtering with if

2

Only Keep What You Want

Sometimes you don't want everything. You only want certain items. The if clause lets you filter.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Only keep even numbers
even_squares = {num: num ** 2 for num in numbers if num % 2 == 0}
print(even_squares)  # {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

# Only numbers greater than 5
big_numbers = {num: num ** 2 for num in numbers if num > 5}
print(big_numbers)  # {6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

# With strings — words longer than 5 characters
words = ["apple", "banana", "cherry", "date", "elderberry"]
long_words = {word: len(word) for word in words if len(word) > 5}
print(long_words)  # {'banana': 6, 'cherry': 6, 'elderberry': 10}

How it works:

  • The if checks each item
  • Only items that pass the test are included
  • Items that don't pass are skipped
  • You can combine this with transformation

Quick Check: What does the if clause do? (Answer: It filters items — only those that satisfy the condition are included)

if-else in Expression

3

Deciding Values Based on Conditions

Sometimes you want different values depending on the item. You can use if-else inside the expression part.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Label numbers as "even" or "odd"
labels = {num: "even" if num % 2 == 0 else "odd" for num in numbers}
print(labels)  # {1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd', 6: 'even', 7: 'odd', 8: 'even', 9: 'odd', 10: 'even'}

# Mark numbers greater than 5 as "high", others as "low"
categories = {num: "high" if num > 5 else "low" for num in numbers}
print(categories)  # {1: 'low', 2: 'low', 3: 'low', 4: 'low', 5: 'low', 6: 'high', 7: 'high', 8: 'high', 9: 'high', 10: 'high'}

# Square even numbers, leave odd numbers as they are
processed = {num: num ** 2 if num % 2 == 0 else num for num in numbers}
print(processed)  # {1: 1, 2: 4, 3: 3, 4: 16, 5: 5, 6: 36, 7: 7, 8: 64, 9: 9, 10: 100}

Important difference:

  • if at the end — filters items out completely
  • if-else in expression — changes the value but keeps the item

Quick Check: What's the difference between if at the end and if-else in expression? (Answer: if at the end filters; if-else in expression transforms)

Nested Dictionary Comprehension

4

Working with Nested Loops

You can use nested loops in dictionary comprehension, just like you would with regular loops.

# Create a multiplication table
table = {i: {j: i * j for j in range(1, 4)} for i in range(1, 4)}
print(table)
# {1: {1: 1, 2: 2, 3: 3}, 2: {1: 2, 2: 4, 3: 6}, 3: {1: 3, 2: 6, 3: 9}}

# Flatten a matrix with indices
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = {(i, j): matrix[i][j] for i in range(3) for j in range(3)}
print(flattened)
# {(0, 0): 1, (0, 1): 2, (0, 2): 3, (1, 0): 4, (1, 1): 5, (1, 2): 6, (2, 0): 7, (2, 1): 8, (2, 2): 9}

# List of lists to dictionary with indices
data = [["apple", "banana"], ["cherry", "date"]]
result = {i: {j: item for j, item in enumerate(row)} for i, row in enumerate(data)}
print(result)
# {0: {0: 'apple', 1: 'banana'}, 1: {0: 'cherry', 1: 'date'}}

Tips:

  • Nested comprehension follows the same order as nested loops
  • It can get hard to read with too many levels
  • Sometimes a regular loop is easier to understand

Multiple Conditions

5

Combining Filters

You can use multiple if clauses or combine conditions with and and or.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Multiple if clauses (acts as AND)
result = {num: num ** 2 for num in numbers if num > 3 if num < 8}
print(result)  # {4: 16, 5: 25, 6: 36, 7: 49}

# Using and
result = {num: num ** 2 for num in numbers if num > 3 and num < 8}
print(result)  # {4: 16, 5: 25, 6: 36, 7: 49}

# Using or
result = {num: num ** 2 for num in numbers if num % 2 == 0 or num > 7}
print(result)  # {2: 4, 4: 16, 6: 36, 8: 64, 9: 81, 10: 100}

Keep it simple:

  • Multiple if clauses are less common
  • Using and and or is usually clearer
  • Don't overcomplicate — readability matters

Swapping Keys and Values

6

Flipping Your Dictionary

One common use of dictionary comprehension is swapping keys and values. This is useful when you need to look up by the value instead of the key.

# Swap keys and values
original = {"apple": 5, "banana": 3, "cherry": 8}
swapped = {value: key for key, value in original.items()}
print(swapped)  # {5: 'apple', 3: 'banana', 8: 'cherry'}

# Be careful with duplicate values (last one wins)
colors = {"red": "#FF0000", "green": "#00FF00", "blue": "#0000FF"}
color_names = {value: key for key, value in colors.items()}
print(color_names)  # {'#FF0000': 'red', '#00FF00': 'green', '#0000FF': 'blue'}

# With a condition
scores = {"Alice": 85, "Bob": 92, "Charlie": 78}
reversed_scores = {score: name for name, score in scores.items() if score >= 80}
print(reversed_scores)  # {85: 'Alice', 92: 'Bob'}

Things to watch out for:

  • If two keys have the same value, one will be lost
  • Values must be hashable to be used as keys
  • This is a great way to create a reverse lookup

Quick Check: What happens if two keys have the same value when swapping? (Answer: The last one overwrites the first)

Common Mistakes

7

Things to Watch Out For

Confusing Filter and Transformation

# WRONG — trying to use if-else as a filter
numbers = [1, 2, 3, 4, 5]
# result = {num: num ** 2 if num % 2 == 0 for num in numbers}  # SyntaxError

# CORRECT — if-else in expression, if at end for filtering
result = {num: num ** 2 for num in numbers if num % 2 == 0}  # Filter
result = {num: "even" if num % 2 == 0 else "odd" for num in numbers}  # Transform

Using the Wrong Variable

# WRONG — using x when you meant num
numbers = [1, 2, 3, 4, 5]
# squares = {num: x ** 2 for x in numbers}  # num is not defined

# CORRECT — use the same variable name
squares = {num: num ** 2 for num in numbers}

Overcomplicating Things

# TOO COMPLEX — hard to read
result = {x: x ** 2 if x % 2 == 0 else x ** 3 if x % 3 == 0 else x for x in range(1, 20)}

# BETTER — use a regular loop for complex logic
result = {}
for x in range(1, 20):
    if x % 2 == 0:
        result[x] = x ** 2
    elif x % 3 == 0:
        result[x] = x ** 3
    else:
        result[x] = x

Quick Check: When should you avoid dictionary comprehension? (Answer: When the logic gets too complex to read easily)

Try It Yourself

Play with dictionary comprehension in the editor below. Change the code and see what happens.

Loading Pyodide... 0%
Python Code Editor
========================================
DICTIONARY COMPREHENSION PRACTICE
========================================

Numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Words: ['apple', 'banana', 'cherry', 'date', 'elderberry']

1. BASIC COMPREHENSION
Squares: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

2. WITH FILTERING
Even squares: {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

3. IF-ELSE IN EXPRESSION
Labels: {1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd', 6: 'even', 7: 'odd', 8: 'even', 9: 'odd', 10: 'even'}

4. WITH STRINGS
Word lengths: {'apple': 5, 'banana': 6, 'cherry': 6, 'date': 4, 'elderberry': 10}

5. SWAPPING KEYS AND VALUES
Original: {'apple': 5, 'banana': 3, 'cherry': 8}
Swapped: {5: 'apple', 3: 'banana', 8: 'cherry'}

Dictionary comprehension practice complete!
🏆

You've Got It!

You now understand dictionary comprehension — basic syntax, filtering, if-else, nested comprehension, and swapping keys and values. These are handy skills for working with dictionaries.

Quick Quiz

Test what you've learned:

1. What is the correct syntax for dictionary comprehension?
2. What does the if clause at the end of a comprehension do?
3. What's the difference between if at the end and if-else in expression?
4. How do you swap keys and values in a dictionary?
5. When should you avoid dictionary comprehension?

Frequently Asked Questions

What is dictionary comprehension? ▼

It's a way to create dictionaries in one line. You write {key: value for item in iterable} and Python builds the dictionary for you.

What's the difference between if at the end and if-else in expression? ▼

if at the end filters items out. if-else in expression changes the value but keeps the item.

Can I use nested comprehension? ▼

Yes, but be careful. It can get hard to read. If it's too complex, a regular loop might be easier to understand.

Is dictionary comprehension faster than a loop? ▼

Usually yes, for simple cases. But readability matters more than speed in most situations.

What happens if I use duplicate keys in comprehension? ▼

The last value for a key overwrites any previous ones. This is the same as regular dictionary behavior.

Can I use dictionary comprehension with nested loops? ▼

Yes, you can. The loops are written in the same order as nested for loops. Just make sure it stays readable.

Where to Go From Here

Now that you've got dictionary comprehension down, check out these related topics:

Dictionary Assignments

Practice what you've learned with assignments.

Learn More →

List Comprehension

Create lists concisely with comprehension.

Learn More →

Set Comprehension

Create sets using comprehension syntax.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
Previous: Nested Dictionaries Next: Dictionary Assignments →