Dictionary and set comprehensions
You already build lists with
[expr for item in iterable]. Python lets you swap that square bracket pair for curly braces to create dictionaries and sets directly. This removes the boilerplate for loop, keeping your logic in a single readable expression while still giving you full control over what goes into each new container.Dictionary comprehensions
users = ['alice', 'bob', 'carol']
scores = {name: len(name) * 10 for name in users}
print(scores)The syntax is
{key_expr : value_expr for item in iterable}. Each pass through the loop creates one key-value pair and drops it into the new dictionary. This example did three things at once: iterated over names, calculated a score based on name length, and stored each result under its username.all_users = {'alice': 30, 'bob': 15, 'carol': 40}
veterans = {name: score for name, score in all_users.items() if score >= 20}
print(veterans)You can add an
if clause at the end to skip items you do not want. This filtered out Bob because his score of 15 fell below your threshold.Set comprehensions
sentence = ['the', 'quick', 'brown', 'fox']
unique_lengths = {len(word) for word in sentence}
print(unique_lengths)A set comprehension uses curly braces but no colon. Because sets only store unique values, duplicates vanish automatically. This collected the lengths 3 and 5 into a single unordered collection, ignoring that 'the' and 'fox' both have length 3.
Inverting dictionaries
temps = {'morning': 12, 'noon': 25, 'evening': 18}
inverted = {value: key for key, value in temps.items()}
print(inverted)You iterate over
.items() to unpack both sides of each pair, then place the old value as the new key. This let you look up which time-of-day produced a specific temperature.You now have a direct way to transform collections without temporary variables or multi-line loops. Use these comprehensions when you need to reshape data for display, filtering, or lookup tables; they keep your code tight and your intent obvious at a glance.