|
| Home |
|---|
Dictionary comprehension is a powerful Python feature that allows programmers to create dictionaries quickly using a single line of code.
It works similarly to list comprehension, but instead of producing a list, it creates a dictionary consisting of key-value pairs.
Dictionary comprehension is often used to transform data, generate mappings, or process collections efficiently.
The general syntax of dictionary comprehension is:
{key_expression : value_expression for item in iterable}
You can also include conditions inside dictionary comprehension.
{key_expression : value_expression for item in iterable if condition}
A common example is generating squares of numbers.
squares = {x: x*x for x in range(6)}
print(squares)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Each number becomes a key and its square becomes the value.
Dictionary comprehension can convert lists into dictionaries.
numbers = [1,2,3,4]
data = {n: n*n for n in numbers}
print(data)
{1: 1, 2: 4, 3: 9, 4: 16}
names = ["Alice","Bob","Charlie"]
scores = [90,85,95]
result = {names[i]:scores[i] for i in range(len(names))}
print(result)
{'Alice': 90, 'Bob': 85, 'Charlie': 95}
You can filter elements using conditions.
numbers = range(10)
even_squares = {x: x*x for x in numbers if x % 2 == 0}
print(even_squares)
{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Dictionary comprehension can transform data values.
celsius = {"day1":20,"day2":25,"day3":30}
fahrenheit = {day:(temp*9/5)+32 for day,temp in celsius.items()}
print(fahrenheit)
{'day1': 68.0, 'day2': 77.0, 'day3': 86.0}
word = "python"
letters = {c:ord(c) for c in word}
print(letters)
{'p':112,'y':121,'t':116,'h':104,'o':111,'n':110}
Dictionary comprehension can reverse key-value pairs.
data = {"a":1,"b":2,"c":3}
reverse = {v:k for k,v in data.items()}
print(reverse)
{1:'a',2:'b',3:'c'}
scores = {"Alice":90,"Bob":70,"Charlie":95,"David":60}
passed = {name:score for name,score in scores.items() if score >= 80}
print(passed)
{'Alice':90,'Charlie':95}
Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.
Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.
Home Tutorial Online Live Trainings Contact Us © 2026 All rights reserved by www.PythonTutor.net