---
title: Tuples, dictionaries and sets
heading: Looking things up by name
eyebrow: A4 · Lesson 13 · Tuples, dictionaries and sets
xp: 40
---

::: hook
A bill of materials maps part names to values: R1 is 4.7 kΩ, C3 is 100 nF. A resistor color code maps colors to digits. A netlist needs the set of every node name, with no repeats. Lists are the wrong shape for these: you don't want "item number 7", you want "the value of R1". Python's dictionary looks values up by a key, its set keeps unique items, and its tuple packages a few values that belong together.
:::

::: predict
## `parts = {"R1": 4700, "C1": 1e-7}`. What is `parts["R1"]`?

- [x] `4700`
- [ ] `"R1"`
- [ ] `("R1", 4700)`
- [ ] An error, because dictionaries have no order

::: reveal
`4700`. A dictionary maps each **key** to a **value**, and square brackets with a key look the value up directly, however many entries there are.
:::
:::

::: nameit
## Tuples

A **tuple** is like a list that can't be changed: `pt = (3, 4)`. Use one for a fixed bundle of values, like a point, an (r, θ) pair, or a function's several results. Tuples unpack: `x, y = pt`.

## Dictionaries

A **dictionary** maps keys (usually strings or numbers) to values:

```
parts = {"R1": 4700, "R2": 10000, "C1": 1e-7}
parts["R1"]               # 4700
parts["R3"] = 2200        # add or replace
"C1" in parts             # True
parts.get("L1", 0)        # 0: a default when the key is missing
len(parts)                # 4
```

Loop over the items:

```
for name, value in parts.items():
    print(name, value)
```

**Counting** is a classic use: start each key at 0 and add one each time you see it.

```
counts = {}
for c in "RRCLRC":
    counts[c] = counts.get(c, 0) + 1     # {'R': 3, 'C': 2, 'L': 1}
```

**Looking up by meaning.** The resistor color code is a dictionary:

```
DIGIT = {"black": 0, "brown": 1, "red": 2, "orange": 3, "yellow": 4,
         "green": 5, "blue": 6, "violet": 7, "grey": 8, "white": 9}
```

so the bands yellow, violet, red are $(4 \times 10 + 7) \times 10^2 = 4700$ Ω.

## Sets

A **set** holds unique items, in no particular order:

```
nodes = {"in", "out", "0"}
nodes.add("mid")
nodes.add("in")           # no effect: already there
a | b, a & b, a - b       # union, intersection, difference
```

Converting a list to a set removes duplicates: `set(["in", "out", "in"])` is `{"in", "out"}`. Checking `x in s` is fast even for huge sets.
:::

::: example
## Decode the color bands brown, black, orange.

::: solution
1. **Look up each band's digit.** The first two bands are digits, and the third is the power of ten.

```
bands = ["brown", "black", "orange"]
value = (DIGIT[bands[0]] * 10 + DIGIT[bands[1]]) * 10 ** DIGIT[bands[2]]
print(value)      # 10000
```

2. **Build the value.** Two digits, 1 and 0, then a multiplier of $10^3$:
   $$\begin{aligned} R &= 10 \times 10^3\ \Omega \\ &= 10\ \text{k}\Omega \end{aligned}$$

**Answer:** brown, black, orange is 10 kΩ.
:::
:::

::: example
## List the distinct nodes in a netlist.

::: solution
1. **Unpack each part and add its nodes to a set.** Each part is a tuple, unpacked in the loop.

```
netlist = [("R1", "in", "mid"), ("R2", "mid", "0"), ("C1", "mid", "0")]
nodes = set()
for name, a, b in netlist:
    nodes.add(a)
    nodes.add(b)
print(sorted(nodes))      # ['0', 'in', 'mid']
```

2. **Let the set drop repeats.** The set ignores repeats, so `mid` and `0` appear once however many parts touch them.

**Answer:** the distinct nodes are `0`, `in` and `mid`.
:::
:::

::: check
kind: python
given: k = 0..9 int

## Using the `DIGIT` dictionary in the starter, write `decode(b1, b2, mult)` for a three-band resistor. Then set `value` for the bands the starter picks.

```python starter
DIGIT = {"black": 0, "brown": 1, "red": 2, "orange": 3, "yellow": 4,
         "green": 5, "blue": 6, "violet": 7, "grey": 8, "white": 9}
bands = [("yellow", "violet", "red"), ("brown", "black", "orange"), ("red", "red", "brown"),
         ("orange", "white", "yellow"), ("blue", "grey", "black"), ("green", "blue", "red"),
         ("brown", "green", "green"), ("grey", "red", "orange"), ("white", "brown", "brown"),
         ("violet", "blue", "black")][k]

def decode(b1, b2, mult):
    return DIGIT[b1] + DIGIT[b2] + DIGIT[mult]

value = decode(*bands)
print(bands, value)
```

```python solution
DIGIT = {"black": 0, "brown": 1, "red": 2, "orange": 3, "yellow": 4,
         "green": 5, "blue": 6, "violet": 7, "grey": 8, "white": 9}
bands = [("yellow", "violet", "red"), ("brown", "black", "orange"), ("red", "red", "brown"),
         ("orange", "white", "yellow"), ("blue", "grey", "black"), ("green", "blue", "red"),
         ("brown", "green", "green"), ("grey", "red", "orange"), ("white", "brown", "brown"),
         ("violet", "blue", "black")][k]

def decode(b1, b2, mult):
    return (DIGIT[b1] * 10 + DIGIT[b2]) * 10 ** DIGIT[mult]

value = decode(*bands)
print(bands, value)
```

```python tests
assert decode("yellow", "violet", "red") == 4700, "Yellow, violet, red is 47 × 10² = 4700 Ω: the first band is tens, the second units, the third a power of ten."
assert decode("brown", "black", "black") == 10, "Brown, black, black is 10 Ω."
```

::: right
Right. The dictionary turns names into digits; the formula is the same as reading any two-digit number with an exponent.
:::
:::

::: check
kind: python
given: k = 0..3 int

## Count how many of each kind of part (the first letter of each name) the list holds. Set `counts` to a dictionary like `{"R": 3, "C": 2}`.

```python starter
names = [["R1", "R2", "C1", "R3", "C2", "L1"], ["C1", "C2", "C3", "R1"],
         ["R1", "Q1", "Q2", "R2", "D1"], ["L1", "L2", "C1", "R1", "R2", "R3", "R4"]][k]
counts = {}
print(counts)
```

```python solution
names = [["R1", "R2", "C1", "R3", "C2", "L1"], ["C1", "C2", "C3", "R1"],
         ["R1", "Q1", "Q2", "R2", "D1"], ["L1", "L2", "C1", "R1", "R2", "R3", "R4"]][k]
counts = {}
for n in names:
    counts[n[0]] = counts.get(n[0], 0) + 1
print(counts)
```

```python tests
names = [["R1", "R2", "C1", "R3", "C2", "L1"], ["C1", "C2", "C3", "R1"],
         ["R1", "Q1", "Q2", "R2", "D1"], ["L1", "L2", "C1", "R1", "R2", "R3", "R4"]][k]
want = {}
for n in names:
    want[n[0]] = want.get(n[0], 0) + 1
assert counts == want, f"counts should be {want}. Use counts.get(letter, 0) + 1 for each name."
```

::: right
Right. `get` with a default is the standard way to count with a dictionary.
:::
:::

::: check
kind: python
given: k = 0..2 int

## Set `nodes` to the set of every node in the netlist, and `n` to how many there are.

```python starter
netlist = [[("R1", "in", "a"), ("R2", "a", "0"), ("C1", "a", "out"), ("R3", "out", "0")],
           [("V1", "in", "0"), ("R1", "in", "x"), ("D1", "x", "0")],
           [("R1", "1", "2"), ("R2", "2", "3"), ("R3", "3", "1"), ("R4", "3", "0"), ("C1", "2", "0")]][k]
nodes = set()
n = 0
print(nodes, n)
```

```python solution
netlist = [[("R1", "in", "a"), ("R2", "a", "0"), ("C1", "a", "out"), ("R3", "out", "0")],
           [("V1", "in", "0"), ("R1", "in", "x"), ("D1", "x", "0")],
           [("R1", "1", "2"), ("R2", "2", "3"), ("R3", "3", "1"), ("R4", "3", "0"), ("C1", "2", "0")]][k]
nodes = set()
for name, a, b in netlist:
    nodes.add(a)
    nodes.add(b)
n = len(nodes)
print(nodes, n)
```

```python tests
want = [{"in", "a", "0", "out"}, {"in", "0", "x"}, {"1", "2", "3", "0"}][k]
assert nodes == want, f"nodes should be {sorted(want)}. Add both ends of every part to a set."
assert n == len(want), "n should be the number of distinct nodes."
```

::: right
Right. A set does the de-duplicating for you.
:::
:::

::: check
kind: python
given: R = 100 | 470 | 2200

## Build `parts` as a dictionary mapping `"R1"` to `R` = {R} and `"R2"` to twice that. Then add `"R3"` equal to the two in series, and set `total` to the sum of all three values.

```python starter
parts = {}
total = 0
print(parts, total)
```

```python solution
parts = {"R1": R, "R2": 2 * R}
parts["R3"] = parts["R1"] + parts["R2"]
total = sum(parts.values())
print(parts, total)
```

```python tests
assert parts.get("R1") == R and parts.get("R2") == 2 * R, "R1 should be R and R2 should be 2R."
assert parts.get("R3") == 3 * R, "R3 should be R1 + R2 in series."
assert total == 6 * R, "total should be the sum of parts.values()."
```

::: right
Right. `values()` gives every value, ready for `sum`.
:::
:::

::: check
kind: python
given: k = 0..2 int

## The starter's netlist is a list of `(part, node_a, node_b)` tuples. Set `on_node` to a dictionary mapping each node name to the sorted list of parts that touch it.

```python starter
nets = [
    [("R1", "in", "a"), ("R2", "a", "gnd"), ("C1", "a", "gnd")],
    [("V1", "in", "gnd"), ("R1", "in", "x"), ("D1", "x", "out"), ("C1", "out", "gnd"), ("R2", "out", "gnd")],
    [("R1", "vcc", "b"), ("R2", "b", "gnd"), ("Q1", "c", "b"), ("R3", "vcc", "c"), ("R4", "e", "gnd"), ("Q1", "e", "b")],
][k]
on_node = {}
for part, a, b in nets:
    on_node[a] = [part]
print(on_node)
```

```python solution
nets = [
    [("R1", "in", "a"), ("R2", "a", "gnd"), ("C1", "a", "gnd")],
    [("V1", "in", "gnd"), ("R1", "in", "x"), ("D1", "x", "out"), ("C1", "out", "gnd"), ("R2", "out", "gnd")],
    [("R1", "vcc", "b"), ("R2", "b", "gnd"), ("Q1", "c", "b"), ("R3", "vcc", "c"), ("R4", "e", "gnd"), ("Q1", "e", "b")],
][k]
on_node = {}
for part, a, b in nets:
    for node in (a, b):
        on_node.setdefault(node, [])
        if part not in on_node[node]:
            on_node[node].append(part)
for node in on_node:
    on_node[node].sort()
print(on_node)
```

```python tests
want = {}
for part, a, b in nets:
    for node in (a, b):
        want.setdefault(node, set()).add(part)
assert isinstance(on_node, dict) and set(on_node) == set(want), f"The nodes should be {sorted(want)}."
for node in want:
    assert on_node[node] == sorted(want[node]), f"Node {node!r} should list {sorted(want[node])}, each part once, sorted."
```

::: right
Right. `setdefault` makes an empty list the first time a node appears, and each part is filed under both of its nodes. Turning a list of connections into a map from node to parts is the first step of every circuit simulator.
:::
:::

::: check
kind: choice

## What is `len({"R1", "R2", "R1", "C1"})`?

- [x] 3
- [ ] 4
- [ ] 2
- [ ] An error, because of the repeated `"R1"`

::: right
Right. A set keeps one copy of each value, so the repeated `"R1"` counts once: `R1`, `R2` and `C1`.
:::

::: misses
- [2] A set drops repeats, so `"R1"` is only stored once.
- [3] There are three different names: `R1`, `R2` and `C1`.
- [4] Repeats in a set literal are allowed. The set simply keeps one copy.
:::
:::

::: explain
## When would you choose a dictionary over a list?

::: model
A list is right when the items are in an order and you find them by position, like samples in time. A dictionary is right when each item has a name or key and you want to look it up by that key, like part values by reference designator or digits by color. With a dictionary you write `parts["R1"]` directly instead of searching a list for the entry that matches.
:::
:::

::: practice

::: check
kind: python
given: k = 0..2 int

## Set `common` to the set of nodes that appear in both lists.

```python starter
a, b = [(["in", "x", "0"], ["x", "out", "0"]), (["1", "2", "3"], ["3", "4"]), (["vcc", "a", "b"], ["b", "c", "vcc"])][k]
common = set()
print(common)
```

```python solution
a, b = [(["in", "x", "0"], ["x", "out", "0"]), (["1", "2", "3"], ["3", "4"]), (["vcc", "a", "b"], ["b", "c", "vcc"])][k]
common = set(a) & set(b)
print(common)
```

```python tests
a, b = [(["in", "x", "0"], ["x", "out", "0"]), (["1", "2", "3"], ["3", "4"]), (["vcc", "a", "b"], ["b", "c", "vcc"])][k]
assert common == set(a) & set(b), "Turn both into sets and take the intersection with &."
```
:::

::: check
kind: python
given: x = 3 | -5 | 8; y = 4 | 12 | 6

## Make the tuple `pt = (x, y)` and then unpack it into `px, py`. Set `d` to the distance from the origin.

```python starter
pt = None
d = 0
print(pt, d)
```

```python solution
pt = (x, y)
px, py = pt
d = (px**2 + py**2) ** 0.5
print(pt, d)
```

```python tests
import math
assert pt == (x, y), "pt should be the tuple (x, y)."
assert math.isclose(d, math.hypot(x, y)), "d should be the distance √(x² + y²)."
```
:::
:::
