hash()1ages = {"Ana": 31, "Ben": 25}2ages["Cy"] = 193ages["Ben"] = 264print(ages["Ana"])5print(ages.get("Zed", 0))6pets = {"cat", "dog", "cat"}7print(len(pets), "dog" in pets)agespetsno 'Zed' → 0already in pets"Cy"'Cy': 1926310"cat"2 True
Code card: ages.py; the highlighted line is the one runninghash(): turns a key into a whole number that says where it belongsTerminal: where print() writesMemory boxes: the pairs of the dict ages and the members of the set petsA dict maps each key to one value; a set keeps each value once. Each step lights the parts it is about. Pairs appear in ages; the new key "Cy" hops into hash(), which works out where it belongs, and the pair hops out to its box; Ben's value crossfades from 25 to 26; looked-up values hop to the terminal. Then cat and dog fill pets, and a second cat is turned away because it is already there.

Build a dict

  1. A dictionary, or dict, stores pairs. Each key points to one value, like a word and its meaning. Line 1 builds ages from two pairs, written key: value inside curly braces.

Look up keys

Sets

Try it yourself

;; step 1/9 · line 1: ages = {"Ana": 31, "Ben": 25}
>>> ages = {"Ana": 31, "Ben": 25}
>>> ages
{'Ana': 31, 'Ben': 25}
>>> len(ages)          # two pairs
2
>>> type(ages)
<class 'dict'>

Dicts keep their keys in the order they were first added (guaranteed since Python 3.7); changing a value keeps the key in its place. Sets keep no order, so a printed set may list its members in any order. Keys and set members must be hashable: numbers, strings and tuples are; lists, dicts and sets are not, because they can change. {[1, 2]} fails with a TypeError that says unhashable type: 'list'.