Dict and Set Comprehensions

The same comprehension syntax that builds lists, building dictionaries and sets instead.

Overview

Three forms, one idea

[n * n for n in nums]    # list
{n * n for n in nums}    # set
{n: n * n for n in nums} # dict

Square brackets build a list. Braces build a set. Braces with a key: value in the expression slot build a dict. The for clause and any trailing if work identically in all three.

dict_comprehension.py

dict_comprehension.py Python 3
Output

                    

set_comprehension.py

set_comprehension.py Python 3
Output

                    

Worth knowing

A colon in the expression makes it a dict comprehension; no colon makes a set.
{} is still an empty dict. There is no empty-set literal.
Duplicate keys are not an error - the last one silently wins.
{v: k for k, v in d.items()} inverts a dictionary in one line.

Dict and Set Comprehensions: A Practical Guide

The comprehension syntax is not a list feature. The same shape builds dictionaries and sets; only the brackets and the expression change.

Dict comprehensions

{w: len(w) for w in words}

The colon is the whole difference. Everything before it is the key, everything after is the value, and both are ordinary expressions evaluated per item.

Two patterns come up constantly. Inverting:

{v: k for k, v in prices.items()}

and building from parallel lists:

{k: v for k, v in zip(keys, values)}

though dict(zip(keys, values)) is shorter when there is no transformation to do.

Duplicate keys do not complain

{k: v for k, v in [("a", 1), ("a", 3)]}

gives {"a": 3}. The later value overwrites the earlier one, with no error and no warning. If the input might contain duplicates and you care, that is something to check for, not something Python will tell you about.

Set comprehensions

{w[0] for w in words}

Braces without a colon. It deduplicates as it builds, which is the point: "the distinct first letters" is one expression rather than a loop plus a set() call.

Remember that a set has no order, so the printed result may not match the input order and should not be relied on.

The empty-braces trap, again

{} is an empty dict — dictionaries claimed the braces long before sets existed. There is no empty-set literal at all; set() is the only way. This is worth repeating because it is the one inconsistency in an otherwise tidy family.

When to use them

Same rule as list comprehensions: when it fits on a line and reads as a sentence. A dict comprehension with a conditional key expression and a filter is a line you will re-read; a loop is fine, and often kinder.

Check yourself

0 of 3

Answer without scrolling back up.

  1. What does `{n for n in [1, 2, 2]}` build?

  2. `{k: v for k, v in [('a', 1), ('a', 2)]}` gives what?

  3. How do you write an empty set comprehension result's type literal?

Cheat sheet

Dict and Set Comprehensions

Square brackets build a list. Braces build a set. Braces with a key: value in the expression slot build a dict. The for clause and any trailing if work identically in all three.

PYTHON · vizlearn.in/python/dict_and_set_comprehensions.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.