Codectionary / Developer documentation / Python

Dictionary & Set Comprehensions

Like list comprehensions, dictionary and set comprehensions provide a concise syntax for building dictionaries and sets from an iterable in a single expression. A dictionary comprehension produces key-value pairs with a colon, while a set comprehension looks like a list comprehension but with curly braces, automatically deduplicating results.

Syntax

{key_expr: value_expr for item in iterable}

Examples

Basic Dictionary Comprehension

Building a dictionary from a list of items.

words = ["apple", "banana", "cherry"]

lengths = {word: len(word) for word in words}
print(lengths)  # {'apple': 5, 'banana': 6, 'cherry': 6}

Dictionary Comprehension with a Condition

Filtering key-value pairs while building the dictionary.

scores = {"Alice": 85, "Bob": 55, "Charlie": 92, "Dave": 40}

passing = {name: score for name, score in scores.items() if score >= 60}
print(passing)  # {'Alice': 85, 'Charlie': 92}

Set Comprehension

Building a set of unique transformed values.

words = ["Hello", "world", "HELLO", "World"]

unique_lower = {word.lower() for word in words}
print(unique_lower)  # {'hello', 'world'}

Swapping Keys and Values

A practical use of dictionary comprehensions: inverting a mapping.

country_codes = {"UK": "United Kingdom", "US": "United States"}

code_lookup = {name: code for code, name in country_codes.items()}
print(code_lookup)  # {'United Kingdom': 'UK', 'United States': 'US'}

Best practices

  • Use dictionary comprehensions to build lookups from another dictionary or a list of tuples, instead of a manual loop with repeated dict[key] = value
  • Remember set comprehensions automatically deduplicate results - useful when transforming values that may collide
  • Keep the key and value expressions simple - extract complex logic into a helper function if it gets hard to read
  • Watch out for accidentally overwriting keys when the key expression isn't unique across items

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading