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

At a glance

Purpose
Scripting and general-purpose applications
File extension
.py
Runs in
Python interpreter
Usually used with
Python standard library and packages

Specifications & further reading

Related Python documentation

Lists
A list is Python's built-in ordered, mutable collection type, created with square brackets. Lists can hold items of any type - even a mix of types - and support indexing, slicing, and a wide range of built-in methods for adding, removing, and reordering elements. Because they are mutable, lists can be changed in place after creation, which makes them the go-to structure for collections that grow or shrink over time.
Tuples
A tuple is an ordered, immutable collection, created with parentheses (or often just commas). Once created, a tuple's contents cannot be changed, added to, or removed - this immutability makes tuples faster than lists and safe to use as dictionary keys or in sets. Tuples are commonly used for fixed collections of related values, like coordinates or RGB colors, and for returning multiple values from a function.
Dictionaries
A dictionary stores data as key-value pairs, created with curly braces. Keys must be unique and hashable (strings, numbers, or tuples are common choices), while values can be anything, including other dictionaries or lists. Since Python 3.7, dictionaries maintain insertion order. They are one of the most heavily used data structures in Python, ideal for representing structured records, lookups, and mappings.
Sets
A set is an unordered collection of unique, hashable items, created with curly braces or the set() function. Sets automatically eliminate duplicates and support fast membership testing, along with mathematical set operations like union, intersection, and difference. They're especially useful for deduplicating data and for comparing two collections to find overlaps or differences.