🎯 Using Dictionary Comprehensions

Dictionary comprehensions provide a concise way to create dictionaries in Python. Understanding this feature is essential for writing efficient and readable code.

# Basic dictionary comprehension
numbers = [1, 2, 3, 4, 5]
squares = {x: x**2 for x in numbers}
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

🎯 Comprehension Syntax

Python dictionary comprehensions follow a specific syntax pattern.

Basic Examples

# Different dictionary comprehension patterns
numbers = [1, 2, 3, 4, 5]

# Basic comprehension
squares = {x: x**2 for x in numbers}
print(f"Squares: {squares}")

# With condition
even_squares = {x: x**2 for x in numbers if x % 2 == 0}
print(f"Even squares: {even_squares}")

# From string
word = "hello"
char_count = {char: word.count(char) for char in word}
print(f"Character count: {char_count}")

# From two lists
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
people = {name: age for name, age in zip(names, ages)}
print(f"People: {people}")

🔍 Advanced Comprehensions

Python allows more sophisticated dictionary comprehension operations.

# Advanced dictionary comprehensions
students = ['Alice', 'Bob', 'Charlie', 'Diana']
scores = [85, 92, 78, 95]

# Nested comprehension
grade_mapping = {'A': 90, 'B': 80, 'C': 70}
student_grades = {
    name: {grade: threshold for grade, threshold in grade_mapping.items() 
           if score >= threshold}
    for name, score in zip(students, scores)
}
print(f"Student grades: {student_grades}")

# Conditional key/value
categorized = {
    name: 'High' if score >= 90 else 'Medium' if score >= 80 else 'Low'
    for name, score in zip(students, scores)
}
print(f"Categorized: {categorized}")

# Transform existing dictionary
original = {'a': 1, 'b': 2, 'c': 3}
transformed = {k.upper(): v * 10 for k, v in original.items()}
print(f"Transformed: {transformed}")

# Multiple conditions
filtered = {
    name: score for name, score in zip(students, scores)
    if len(name) > 3 and score >= 85
}
print(f"Filtered: {filtered}")

🎯 Key Takeaways

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent