A413 of 56
0 XP
  1. Hook
  2. Predict
  3. Name it
  4. Check
  5. Explain

A4 · Lesson 13 · Tuples, dictionaries and sets

Looking things up by name

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"]?

Name it

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×10+7)×102=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.

Worked example

Decode the color bands brown, black, orange.

Show the 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
  1. Build the value. Two digits, 1 and 0, then a multiplier of 103: R=10×103Ω=10kΩ

Answer brown, black, orange is 10 kΩ.

Worked example

List the distinct nodes in a netlist.

Show the 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']
  1. 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

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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

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

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Build parts as a dictionary mapping "R1" to R = 470 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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

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

Explain why

When would you choose a dictionary over a list?

Practice

Keep practicing

7 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.