Dictionary comprehension provides a concise way to create dictionaries from an iterable.
It works similarly to list comprehension, but instead of producing a list, it produces a dictionary containing key-value pairs.
Basic Syntax
{key: value for item in iterable}For example:
numbers = [1, 2, 3, 4, 5]
squares = {
x: x ** 2
for x in numbers
}
print(squares)Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}Here:
x→ item from the iterablex→ dictionary keyx ** 2→ dictionary value{}→ creates a dictionary
1. Basic Dictionary Comprehension
Let's create a dictionary containing numbers and their squares.
numbers = [1, 2, 3, 4, 5]
squares = {
x: x ** 2
for x in numbers
}
print(squares)Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}The equivalent normal for loop is:
numbers = [1, 2, 3, 4, 5]
squares = {}
for x in numbers:
squares[x] = x ** 2
print(squares)Dictionary comprehension provides a shorter way to write this.
2. Create Number and Cube Dictionary
numbers = [1, 2, 3, 4, 5]
cubes = {
x: x ** 3
for x in numbers
}
print(cubes)Output:
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}3. Create Number and Double Dictionary
numbers = [10, 20, 30, 40]
doubled = {
x: x * 2
for x in numbers
}
print(doubled)Output:
{10: 20, 20: 40, 30: 60, 40: 80}4. Dictionary from Two Lists
Suppose we have separate lists of names and marks:
names = ["Ram", "Sita", "Hari", "Gita"]
marks = [75, 85, 65, 90]We can combine them using zip():
students = {
name: mark
for name, mark in zip(names, marks)
}
print(students)Output:
{'Ram': 75, 'Sita': 85, 'Hari': 65, 'Gita': 90}This is a very common use of dictionary comprehension.
5. Dictionary Comprehension with a Condition
Just like list comprehension, dictionary comprehension can use an if condition.
Syntax
{key: value for item in iterable if condition}Example:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = {
x: x ** 2
for x in numbers
if x % 2 == 0
}
print(even_numbers)Output:
{2: 4, 4: 16, 6: 36}Only even numbers are included.
6. Filter Students by Marks
students = {
"Ram": 75,
"Sita": 85,
"Hari": 35,
"Gita": 90
}
passed_students = {
name: marks
for name, marks in students.items()
if marks >= 40
}
print(passed_students)Output:
{'Ram': 75, 'Sita': 85, 'Gita': 90}Here, students with marks below 40 are excluded.
7. Get Students with Distinction
students = {
"Ram": 75,
"Sita": 85,
"Hari": 35,
"Gita": 90
}
distinction = {
name: marks
for name, marks in students.items()
if marks >= 80
}
print(distinction)Output:
{'Sita': 85, 'Gita': 90}8. Modify Dictionary Values
Dictionary comprehension can be used to create a new dictionary with modified values.
students = {
"Ram": 75,
"Sita": 85,
"Hari": 65
}
updated_marks = {
name: marks + 5
for name, marks in students.items()
}
print(updated_marks)Output:
{'Ram': 80, 'Sita': 90, 'Hari': 70}The original dictionary is not modified.
9. Convert Values to Uppercase
students = {
"ram": 75,
"sita": 85,
"hari": 65
}
updated = {
name.upper(): marks
for name, marks in students.items()
}
print(updated)Output:
{'RAM': 75, 'SITA': 85, 'HARI': 65}10. Convert Values to Lowercase
students = {
"RAM": 75,
"SITA": 85,
"HARI": 65
}
updated = {
name.lower(): marks
for name, marks in students.items()
}
print(updated)Output:
{'ram': 75, 'sita': 85, 'hari': 65}11. Create Dictionary of Even and Odd Numbers
We can use an expression with if-else.
numbers = [1, 2, 3, 4, 5]
result = {
x: "Even" if x % 2 == 0 else "Odd"
for x in numbers
}
print(result)Output:
{1: 'Odd', 2: 'Even', 3: 'Odd', 4: 'Even', 5: 'Odd'}Notice that all numbers are included because we are using if-else, not a filter if.
12. Create Number Classification Dictionary
numbers = [-3, -2, -1, 0, 1, 2, 3]
result = {
x: "Positive" if x > 0
else "Negative" if x < 0
else "Zero"
for x in numbers
}
print(result)Output:
{-3: 'Negative', -2: 'Negative', -1: 'Negative', 0: 'Zero', 1: 'Positive', 2: 'Positive', 3: 'Positive'}13. Dictionary Comprehension with range()
squares = {
x: x ** 2
for x in range(1, 6)
}
print(squares)Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}14. Create Multiplication Dictionary
table = {
x: x * 5
for x in range(1, 11)
}
print(table)Output:
{1: 5, 2: 10, 3: 15, 4: 20, 5: 25, 6: 30, 7: 35, 8: 40, 9: 45, 10: 50}15. Dictionary Comprehension from a String
Strings are iterable, so they can also be used.
word = "Python"
result = {
char: ord(char)
for char in word
}
print(result)Output:
{'P': 80, 'y': 121, 't': 116, 'h': 104, 'o': 111, 'n': 110}Here, ord() returns the Unicode code point of a character.
16. Count Characters in a String
A simple dictionary comprehension can create a character-frequency dictionary when combined with count().
word = "banana"
result = {
char: word.count(char)
for char in set(word)
}
print(result)Output:
{'b': 1, 'a': 3, 'n': 2}The order can vary because set is unordered.
For large strings, there are more efficient approaches, which we will cover later when discussing dictionaries and data processing.
17. Swap Dictionary Keys and Values
Suppose we have:
students = {
"Ram": 75,
"Sita": 85,
"Hari": 65
}We can swap the keys and values:
result = {
marks: name
for name, marks in students.items()
}
print(result)Output:
{75: 'Ram', 85: 'Sita', 65: 'Hari'}This only works safely when the values are unique and suitable as dictionary keys.
18. Practical Example : Product Prices
products = {
"Laptop": 80000,
"Mouse": 1500,
"Keyboard": 3000,
"Monitor": 25000
}
discounted = {
product: price * 0.9
for product, price in products.items()
}
print(discounted)Output:
{'Laptop': 72000.0, 'Mouse': 1350.0, 'Keyboard': 2700.0, 'Monitor': 22500.0}Here, every product receives a 10% discount.
19. Filter Expensive Products
products = {
"Laptop": 80000,
"Mouse": 1500,
"Keyboard": 3000,
"Monitor": 25000
}
expensive = {
product: price
for product, price in products.items()
if price > 20000
}
print(expensive)Output:
{'Laptop': 80000, 'Monitor': 25000}20. Practical Example : Employee Salaries
employees = {
"Ram": 35000,
"Sita": 55000,
"Hari": 45000,
"Gita": 70000
}
high_salary = {
name: salary
for name, salary in employees.items()
if salary >= 50000
}
print(high_salary)Output:
{'Sita': 55000, 'Gita': 70000}21. Practical Example : Increase Salaries
employees = {
"Ram": 35000,
"Sita": 55000,
"Hari": 45000
}
updated_salaries = {
name: salary * 1.10
for name, salary in employees.items()
}
print(updated_salaries)Output:
{'Ram': 38500.0, 'Sita': 60500.00000000001, 'Hari': 49500.00000000001}The values are increased by 10%.
22. Dictionary Comprehension with Nested Data
Consider a list of students:
students = [
{"name": "Ram", "marks": 75},
{"name": "Sita", "marks": 85},
{"name": "Hari", "marks": 65}
]We can convert it into a dictionary:
result = {
student["name"]: student["marks"]
for student in students
}
print(result)Output:
{'Ram': 75, 'Sita': 85, 'Hari': 65}This is very useful when converting structured data.
23. Practical Example : Student Status
students = {
"Ram": 75,
"Sita": 35,
"Hari": 65,
"Gita": 90
}
status = {
name: "Pass" if marks >= 40 else "Fail"
for name, marks in students.items()
}
print(status)Output:
{'Ram': 'Pass', 'Sita': 'Fail', 'Hari': 'Pass', 'Gita': 'Pass'}24. Dictionary Comprehension vs Normal Loop
Normal Loop
numbers = [1, 2, 3, 4, 5]
squares = {}
for x in numbers:
squares[x] = x ** 2
print(squares)Dictionary Comprehension
numbers = [1, 2, 3, 4, 5]
squares = {
x: x ** 2
for x in numbers
}
print(squares)Both produce:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}Dictionary comprehension is more compact.
25. Dictionary Comprehension vs map()
We can sometimes use map() to transform dictionary data, but dictionary comprehension is usually more direct when we need to construct key-value pairs.
students = {
"Ram": 75,
"Sita": 85,
"Hari": 65
}
updated = {
name: marks + 5
for name, marks in students.items()
}
print(updated)Output:
{'Ram': 80, 'Sita': 90, 'Hari': 70}26. Combining Dictionary and List Comprehension
We can use comprehensions together.
students = {
"Ram": [75, 80, 85],
"Sita": [85, 90, 95],
"Hari": [60, 65, 70]
}
averages = {
name: sum(marks) / len(marks)
for name, marks in students.items()
}
print(averages)Output:
{'Ram': 80.0, 'Sita': 90.0, 'Hari': 65.0}This is a useful example for processing structured data.
Important Points to Remember
- Dictionary comprehension creates a new dictionary concisely.
- Basic syntax:
{key: value for item in iterable}- It can include a filtering condition:
{key: value for item in iterable if condition}- It can use
if-else:
{key: value_if_true if condition else value_if_false for item in iterable}dict.items()is commonly used when processing an existing dictionary.zip()can combine multiple lists into key-value pairs.- Dictionary comprehension creates a new dictionary.
- It is useful for filtering, transforming, and restructuring data.
Easy way to remember
List Comprehension → []
Dictionary Comprehension → {}
Set Comprehension → {}Basic dictionary comprehension:
{
key: value
for item in iterable
}With filtering:
{
key: value
for item in iterable
if condition
}With if-else:
{
key: value_if_true if condition else value_if_false
for item in iterable
}