typestar

Dict & set comprehensions in Python

The comprehension syntax, aimed at dicts and sets.

words = ["kiwi", "kea", "moa", "tui"]

lengths = {w: len(w) for w in words}
by_length = {len(w): w for w in words}
shouted = {w.upper(): w for w in words if "i" in w}

vowels = {ch for w in words for ch in w if ch in "aeiou"}

scores = {"ada": 95, "grace": 88}
flipped = {v: k for k, v in scores.items()}

How it works

  1. {w: len(w) for w in words} builds key-value pairs.
  2. A {...} with no colon builds a set of unique items.
  3. Flipping {v: k for k, v in ...} swaps keys and values.

Keywords and builtins used here

The run, in numbers

Lines
10
Characters to type
304
Tokens
119
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 75 seconds.

Type this snippet

Step 2 of 4 in Comprehensions, step 2 of 53 in Pythonic Python.

← Previous Next →