Featurecore
Set and dict comprehensions
Also called set comprehension, dict comprehension, dictionary comprehension, setcomp, dictcomp, invert a dict, no tuple comprehension.
A set comprehension is a comprehension in curly braces, and a dict comprehension has a key: value pair before its for clause. They build a set or dict the same way a list comprehension builds a list.
- Language
- Python
Synopsis
letters = {x for x in "abracadabra" if x not in "abc"}
print(sorted(letters))
squares = {x: x ** 2 for x in (2, 4, 6)}
print(squares)
['d', 'r']
{2: 4, 4: 16, 6: 36}
The set comprehension keeps one copy of each letter. The dict comprehension makes a key and a value for each item.
Semantics
r1. "List, set and dictionary comprehensions are a form of container displays where items are computed via a set of looping and filtering instructions rather than listed explicitly."1
r2. "Set comprehensions work similarly." A set comprehension roughly corresponds to a loop that calls result.add() on a new set.1 Example: lower.
r3. "Dictionary comprehensions start with a colon-separated key-value pair instead of an expression."1 "As in other kinds of dictionary displays, the same key may be specified multiple times. Earlier values are overwritten by ones that are evaluated later."1 Example: invert.
r4. "There are no tuple comprehensions. A similar syntax is instead used for generator expressions, from which you can construct a tuple like this".1 Example: tuple.
r5. PEP 274 says: "You can use dict comprehensions in ways very similar to list comprehensions, except that they produce Python dictionary objects instead of list objects."3
r6. The key of each dict entry must be hashable. "You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend()."2 Example: list-key.
Examples
print(sorted({x.lower() for x in ["a", "A", "b", "C"]}))
['a', 'b', 'c']
prices = [("apple", 3), ("pear", 5), ("fig", 2)]
cheap = {name: p for name, p in prices if p < 5}
print(cheap)
print({name: len(name) for name, _ in prices})
{'apple': 3, 'fig': 2}
{'apple': 5, 'pear': 4, 'fig': 3}
The for clause can unpack each pair, and an if clause drops entries.
print(tuple(x ** 2 for x in range(5)))
(0, 1, 4, 9, 16)
Pitfalls
When two items give the same key, the last one wins:
This code runs but gives a wrong answer on purpose.
ages = {"ann": 30, "bob": 25, "cy": 30}
by_age = {age: name for name, age in ages.items()}
print(by_age)
{30: 'cy', 25: 'bob'}
"ann" is lost (rule r3). To keep all names, collect them in lists, for example with collections.defaultdict(list).
A key that is a list is a TypeError:
This code raises TypeError, on purpose.
groups = {[n, n + 1]: n for n in range(3)}
Use a tuple as the key (rule r6).
Comparison
Go has no comprehension syntax. A Go program makes a map with make and fills it in a loop. The Go spec says: "A map is an unordered group of elements of one type, called the element type, indexed by a set of unique keys of another type, called the key type."4 A Python dict comprehension builds the dict in one expression (rule r3).
References
- The Python Language Reference, Python 3.15, 6.2.6. Comprehensions
- The Python Tutorial, 5. Data Structures, 5.4. Sets; 5.5. Dictionaries
- PEP 274: Dict Comprehensions, Abstract
- The Go Programming Language Specification, Map types
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag XJN0DJ Edit this page History Report an error Markdown