In the previous lesson, you learned how to use Python dictionary methods to retrieve, update, and manage dictionary data efficiently. While dictionaries can be created and modified using loops, Python provides a shorter and more elegant way to create dictionaries called dictionary comprehension.
Dictionary comprehension allows you to create dictionaries in a single line of code by combining loops and expressions. It makes programs shorter, easier to read, and often more efficient. Dictionary comprehensions are widely used in data analysis, machine learning, automation, web development, and data transformation.
In this lesson, you will learn what dictionary comprehension is, why it is useful, understand its syntax, compare it with traditional loops, and explore practical real-world examples.
After completing this lesson, you will be able to:
Dictionary comprehension is a compact way to create dictionaries using a single expression. Instead of writing multiple lines with a for loop, you can generate an entire dictionary in one statement.
It follows the same idea as list comprehension but produces a dictionary consisting of key-value pairs.
Dictionary comprehensions are useful because they reduce code, improve readability, and simplify data transformation.
Common applications include:
{
key: value
for item in iterable
}
The expression before the for keyword defines the key and value that will be stored in the dictionary.
squares = {
number: number ** 2
for number in range(1, 6)
}
print(squares)
Output
{
1: 1,
2: 4,
3: 9,
4: 16,
5: 25
}
Each number becomes the key, while its square becomes the corresponding value.
students = [
"Rahul",
"Priya",
"Amit"
]
attendance = {
student: "Present"
for student in students
}
print(attendance)
Output
{
'Rahul': 'Present',
'Priya': 'Present',
'Amit': 'Present'
}
numbers = {
value: value * 10
for value in range(1, 6)
}
print(numbers)
Output
{
1: 10,
2: 20,
3: 30,
4: 40,
5: 50
}
squares = {}
for number in range(1, 6):
squares[number] = number ** 2
print(squares)
Output
{
1: 1,
2: 4,
3: 9,
4: 16,
5: 25
}
squares = {
number: number ** 2
for number in range(1, 6)
}
print(squares)
Output
{
1: 1,
2: 4,
3: 9,
4: 16,
5: 25
}
Both programs produce the same result, but dictionary comprehension requires fewer lines of code.
students = [
"Rahul",
"Priya",
"Amit"
]
marks = {
student: 90
for student in students
}
print(marks)
Output
{
'Rahul': 90,
'Priya': 90,
'Amit': 90
}
products = [
"Laptop",
"Mouse",
"Keyboard"
]
prices = {
product: 1000
for product in products
}
print(prices)
Output
{
'Laptop': 1000,
'Mouse': 1000,
'Keyboard': 1000
}
Consider the following program.
numbers = {
value: value ** 2
for value in range(1, 4)
}
print(numbers)
Execution Steps
range(1, 4).value ** 2 becomes the dictionary value.Output
{
1: 1,
2: 4,
3: 9
}
for loop before the key-value expression.In this section, you learned what Python dictionary comprehension is, why it is useful, its syntax, and how it compares with a traditional for loop. You also explored practical examples, execution flow, and common beginner mistakes. In the next section, you will learn how to use conditional dictionary comprehensions with if and if...else, filter dictionaries, transform keys and values, and apply these techniques in real-world Python programs.
In the previous section, you learned how to create dictionaries using dictionary comprehension. You also compared dictionary comprehensions with traditional for loops and saw how they simplify code. Dictionary comprehensions become even more powerful when combined with conditions, allowing you to filter data and transform keys or values while creating dictionaries.
In this section, you will learn how to use if and if...else statements inside dictionary comprehensions, filter dictionary data, transform keys and values, and apply these techniques to practical real-world examples.
Conditional dictionary comprehensions allow you to include or modify dictionary elements based on specific conditions.
The most common approaches are:
if for filtering.if...else for assigning different values.if in Dictionary ComprehensionThe if condition filters elements before they are added to the dictionary.
{
key: value
for item in iterable
if condition
}
even_squares = {
number: number ** 2
for number in range(1, 11)
if number % 2 == 0
}
print(even_squares)
Output
{
2: 4,
4: 16,
6: 36,
8: 64,
10: 100
}
Only even numbers satisfy the condition and become part of the dictionary.
if...else in Dictionary ComprehensionThe if...else expression assigns different values based on a condition.
{
key: value_if_true if condition else value_if_false
for item in iterable
}
grades = {
marks: "Pass" if marks >= 40 else "Fail"
for marks in [25, 40, 55, 32, 90]
}
print(grades)
Output
{
25: 'Fail',
40: 'Pass',
55: 'Pass',
32: 'Fail',
90: 'Pass'
}
You can create a new dictionary by selecting only the items that satisfy a condition.
students = {
"Rahul": 92,
"Priya": 85,
"Amit": 35,
"Neha": 78
}
passed_students = {
name: marks
for name, marks in students.items()
if marks >= 40
}
print(passed_students)
Output
{
'Rahul': 92,
'Priya': 85,
'Neha': 78
}
Dictionary comprehensions can modify values while keeping the same keys.
prices = {
"Laptop": 50000,
"Mouse": 800,
"Keyboard": 1500
}
discounted_prices = {
product: price * 0.9
for product, price in prices.items()
}
print(discounted_prices)
Output
{
'Laptop': 45000.0,
'Mouse': 720.0,
'Keyboard': 1350.0
}
You can also transform dictionary keys while preserving the values.
students = {
"rahul": 92,
"priya": 85,
"amit": 90
}
formatted = {
name.title(): marks
for name, marks in students.items()
}
print(formatted)
Output
{
'Rahul': 92,
'Priya': 85,
'Amit': 90
}
salaries = {
"Rahul": 50000,
"Priya": 60000,
"Amit": 45000
}
tax = {
name: salary * 0.10
for name, salary in salaries.items()
}
print(tax)
Output
{
'Rahul': 5000.0,
'Priya': 6000.0,
'Amit': 4500.0
}
attendance = {
"Rahul": 92,
"Priya": 68,
"Amit": 81
}
status = {
name: "Eligible" if percent >= 75 else "Not Eligible"
for name, percent in attendance.items()
}
print(status)
Output
{
'Rahul': 'Eligible',
'Priya': 'Not Eligible',
'Amit': 'Eligible'
}
numbers = {
number: number ** 2
for number in range(1, 11)
if number % 2 == 0
}
print(numbers)
Output
{
2: 4,
4: 16,
6: 36,
8: 64,
10: 100
}
Consider the following program.
numbers = {
value: value ** 2
for value in range(1, 6)
if value % 2 == 1
}
print(numbers)
Execution Steps
range(1, 6).if condition.Output
{
1: 1,
3: 9,
5: 25
}
if condition before the for loop.if with conditional if...else expressions.In this section, you learned how to use conditional dictionary comprehensions with if and if...else, filter dictionaries, transform keys and values, and apply these techniques in practical Python programs. You also explored execution flow and common beginner mistakes. In the next section, you will learn nested dictionary comprehensions, create dictionaries using zip() and enumerate(), explore real-world applications, and review best practices and performance tips.
In the previous section, you learned how to create conditional dictionary comprehensions using if and if...else expressions. You also learned how to filter dictionary data and transform keys and values. Dictionary comprehension becomes even more powerful when combined with functions such as zip() and enumerate(), allowing you to create dictionaries from multiple iterables efficiently.
In this section, you will learn advanced dictionary comprehension techniques, including nested dictionary comprehensions, creating dictionaries from lists and strings, using zip() and enumerate(), and exploring real-world applications, best practices, and performance tips.
Dictionary comprehensions can be combined with built-in Python functions to create structured dictionaries from different types of data.
zip()The zip() function combines two or more iterables into pairs. It is commonly used with dictionary comprehension.
students = [
"Rahul",
"Priya",
"Amit"
]
marks = [
92,
85,
90
]
student_marks = {
student: mark
for student, mark in zip(students, marks)
}
print(student_marks)
Output
{
'Rahul': 92,
'Priya': 85,
'Amit': 90
}
enumerate()The enumerate() function provides both the index and the value while iterating.
subjects = [
"Python",
"SQL",
"Power BI"
]
subject_ids = {
index + 1: subject
for index, subject in enumerate(subjects)
}
print(subject_ids)
Output
{
1: 'Python',
2: 'SQL',
3: 'Power BI'
}
You can iterate through characters in a string while creating a dictionary.
word = "DATA"
letters = {
character: ord(character)
for character in word
}
print(letters)
Output
{
'D': 68,
'A': 65,
'T': 84
}
Duplicate characters automatically overwrite previous keys because dictionary keys must be unique.
Dictionary comprehensions can also generate nested dictionaries.
students = {
student: {
"Marks": 90,
"Status": "Pass"
}
for student in [
"Rahul",
"Priya",
"Amit"
]
}
print(students)
Output
{
'Rahul': {'Marks': 90, 'Status': 'Pass'},
'Priya': {'Marks': 90, 'Status': 'Pass'},
'Amit': {'Marks': 90, 'Status': 'Pass'}
}
products = [
"Laptop",
"Mouse",
"Keyboard"
]
inventory = {
product: 100
for product in products
}
print(inventory)
Output
{
'Laptop': 100,
'Mouse': 100,
'Keyboard': 100
}
employees = [
"Neha",
"Rahul",
"Priya"
]
employee_ids = {
index + 101: employee
for index, employee in enumerate(employees)
}
print(employee_ids)
Output
{
101: 'Neha',
102: 'Rahul',
103: 'Priya'
}
students = [
"Rahul",
"Priya",
"Amit"
]
grades = [
"A",
"B",
"A"
]
result = {
student: grade
for student, grade in zip(students, grades)
}
print(result)
Output
{
'Rahul': 'A',
'Priya': 'B',
'Amit': 'A'
}
zip() when combining multiple iterables.enumerate() when indexes are required.for loop when the logic becomes too complex.Consider the following program.
numbers = {
number: number * 10
for number in range(1, 5)
}
print(numbers)
Execution Steps
number * 10 becomes the corresponding value.Output
{
1: 10,
2: 20,
3: 30,
4: 40
}
zip() stops when the shortest iterable ends.enumerate() incorrectly when custom indexing is required.In this section, you learned advanced dictionary comprehension techniques, including creating dictionaries using zip() and enumerate(), generating dictionaries from strings, creating nested dictionaries, and applying dictionary comprehensions in real-world scenarios. You also explored best practices, performance tips, execution flow, and common beginner mistakes. In the final section, you will review the complete lesson through a lesson summary, key takeaways, FAQs, coding exercises, interview questions, a mini project, and a preview of the next lesson on Nested Dictionaries: Complete Guide for Beginners.
In this lesson, you learned how to create dictionaries using Python dictionary comprehension, a concise and efficient alternative to traditional for loops. Dictionary comprehensions allow you to generate dictionaries in a single expression, making your code shorter, more readable, and easier to maintain.
You began by understanding the syntax of dictionary comprehension and learned how to create dictionaries from ranges and lists. You also compared dictionary comprehensions with traditional loops and discovered when each approach should be used.
Next, you explored conditional dictionary comprehensions using if and if...else expressions. You learned how to filter dictionary data, transform keys and values, and create dictionaries based on specific conditions.
Finally, you learned advanced techniques such as creating dictionaries using zip() and enumerate(), generating dictionaries from strings, creating nested dictionaries, and applying dictionary comprehensions to real-world programming tasks. You also reviewed best practices, performance tips, and common beginner mistakes.
Dictionary comprehensions are widely used in data analysis, machine learning, automation, web development, and data processing because they simplify dictionary creation while improving code readability.
key: value syntax.if to filter dictionary items.if...else to assign conditional values.zip() to combine multiple iterables.enumerate() when indexes are required.Dictionary comprehension is a concise way to create dictionaries using a single expression.
Curly braces {} with a key: value expression.
Yes. Both if and if...else expressions are supported.
for loops?For simple dictionary creation and transformations, yes.
zip()?It combines multiple iterables so they can be processed together.
enumerate() useful?It provides both the index and the value during iteration.
Yes. The value expression can itself be another dictionary.
The last value assigned to the duplicate key overwrites the previous value.
For many simple operations, they are generally faster and more concise.
Avoid it when the logic becomes too complex and reduces code readability.
if...else to assign pass or fail grades.zip().enumerate().for loop?if in dictionary comprehension?if...else in dictionary comprehension?zip() be used with dictionary comprehension?enumerate()?Create a Python program that manages student grades using dictionary comprehension.
Your program should:
zip().if...else.enumerate().========== STUDENT GRADE MANAGEMENT ==========
Student Marks
{'Rahul': 92, 'Priya': 85, 'Amit': 35}
Pass / Fail Status
{'Rahul': 'Pass', 'Priya': 'Pass', 'Amit': 'Fail'}
Passed Students
{'Rahul': 92, 'Priya': 85}
Student IDs
{1: 'Rahul', 2: 'Priya', 3: 'Amit'}
Nested Dictionary
{
'Rahul': {'Marks': 92, 'Status': 'Pass'},
'Priya': {'Marks': 85, 'Status': 'Pass'},
'Amit': {'Marks': 35, 'Status': 'Fail'}
}
=============================================
Congratulations! You have successfully mastered Python Dictionary Comprehension. You can now create dictionaries efficiently, filter and transform data, combine iterables using zip(), generate indexed dictionaries using enumerate(), and build nested dictionaries using concise Python syntax.
In the next lesson, you will learn Nested Dictionaries: Complete Guide for Beginners. You will explore how to create nested dictionaries, access nested values, update nested data, iterate through multiple levels of dictionaries, and use nested dictionaries in real-world Python applications.