PYTHON

Concise Dictionary Creation and Transformation with Comprehensions

Learn to build and transform dictionaries efficiently using dictionary comprehensions in Python. Ideal for quick data restructuring, filtering, and mapping key-value pairs.

students_scores = {'Alice': 88, 'Bob': 92, 'Charlie': 75, 'David': 95}

# 1. Create a new dictionary from an existing one, filtering and transforming values
#    Get students who scored 90+ and assign 'A' grade
high_achievers = {
    name: 'A' for name, score in students_scores.items() if score >= 90
}
print(f"High achievers (A grade): {high_achievers}")

# 2. Swap keys and values (if values are unique)
score_to_student = {
    score: name for name, score in students_scores.items()
}
print(f"Scores mapped to students: {score_to_student}")

# 3. Create a dictionary from two lists (keys and values)
keys = ['apple', 'banana', 'cherry']
values = [1.2, 0.8, 2.5]
fruit_prices = {
    key: value for key, value in zip(keys, values)
}
print(f"Fruit prices: {fruit_prices}")

# 4. Conditional key-value transformation
status_by_score = {
    name: 'Excellent' if score >= 90 else 'Good' for name, score in students_scores.items()
}
print(f"Student status by score: {status_by_score}")
How it works: Dictionary comprehensions provide a powerful and expressive syntax for creating new dictionaries. This snippet illustrates how to efficiently filter key-value pairs, transform values, swap keys and values, and construct dictionaries from iterables like lists. They are a concise and Pythonic alternative to traditional loops, enhancing both code clarity and performance when generating or manipulating dictionary data.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs