Skip to content
UPEEC

Dictionary and Set Comprehensions

Build dicts and sets in one expression, like list comprehensions.

Easy
Comments 0
squares = {n: n * n for n in range(5)}         # {0: 0, 1: 1, 2: 4, …}
unique_lengths = {len(w) for w in words}        # a set
inverted = {v: k for k, v in pins.items()}      # swap keys and values

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.