Python 3D Academyবাংলা

Set and dictionary comprehensions

🌍 In real life. A teacher asks: "Which first letters do your names start with?" She only wants each letter once: that's a set. Then: "Write each name with its length", one entry per name: that's a dictionary. The same quick recipe works for both.

The idea in one sentence: with curly braces, a comprehension builds a set ({expression for ...}) or, with key: value at the front, a dictionary ({key: value for ...}).

Its words:

  • set comprehension: {w[0] for w in words}; repeats are dropped
  • dict comprehension: {w: len(w) for w in words}; one key per item, a later key overwriting an earlier one
  • .items() in a comprehension: loop over another dictionary's pairs

Step by step, for {w: len(w) for w in ["fig", "kiwi"]}:

  1. w is "fig": add the pair "fig": 3.
  2. w is "kiwi": add "kiwi": 4.
  3. The result is {'fig': 3, 'kiwi': 4}.
words = ["ant", "bee", "ape"]
firsts = {w[0] for w in words}
print(sorted(firsts))

Write key: value at the front and you get a dictionary: {key: value for name in source}.

words = ["fig", "kiwi", "plum"]
lengths = {w: len(w) for w in words}
print(lengths)
squares = {n: n * n for n in range(1, 4)}
print(squares)

A dictionary comprehension can loop over another dictionary's items(), unpacking each pair, and can filter too:

prices = {"pen": 10, "book": 50, "gum": 5}
cheap = {item: p for item, p in prices.items() if p < 20}
print(cheap)
flipped = {p: item for item, p in prices.items()}
print(flipped)

How Python tells them apart. Square brackets make a list. Curly braces make a set, unless the expression has a colon, key: value, which makes a dictionary. Each one costs one lap per source item, plus a quick hash lookup to drop repeats or place keys.

Mistakes and edge cases.

  • Repeated keys. Flipping {"pen": 10, "cup": 10} into {p: item ...} keeps only one of them: both want the key 10, and the later one wins.
  • {} isn't an empty set. Even from a comprehension, an empty result {x for x in []} is set(), but writing {} yourself makes a dictionary.
  • A list where you wanted a set. [n for n in nums] keeps repeats; use {n for n in nums} to count different values (see the bug question).
  • Expecting order from a set. Use sorted(...) when you print one.

Quiz

  1. What does this print?

    print(sorted({x % 3 for x in range(7)}))
  2. What does this print?

    print({w: len(w) for w in ["a", "bb"]})
  3. What does this print?

    print({n: n * 10 for n in range(2)})
  4. What does {x: 0 for x in names} make?

    • A dictionary
    • A set
    • A list
  5. What does this print?

    d = {"a": 1, "b": 2}
    print({v: k for k, v in d.items()})
  6. This should print how many different numbers there are, 2, but it prints 3. Which line has the mistake?

    nums = [3, 1, 3]
    unique = [n for n in nums]
    print(len(unique))

Coding tasks

  1. Ask for some words on one line. Print a dictionary where each word leads to its length.

  2. Ask for some words on one line. Print the sorted list of the different word lengths.

  3. Ask for a number n, then for n sentences, one per line. Print the largest number of words found in any one sentence.