Dictionaries and sets
A list finds things by position. A dictionary finds them by name: it stores key: value pairs, so ages["Ana"] gives Ana's age straight away. Step through a seven-line program, ages.py, that builds a dict, adds a pair, changes a value, looks keys up (safely, with get()), then builds a set and watches it drop a duplicate. Along the way, see the trick that makes both fast: Python hashes each key to work out where it belongs.
5 quick questions
Pick an answer to see why. Your score saves with your progress.
01After d = {"a": 1} and then d["a"] = 5 , what is d?
Keys are unique. Assigning to a key that already exists replaces its value, so d holds one pair, 'a': 5.
02ages = {"Ana": 31}. What does ages.get("Zed", 0) give?
get() returns the default you pass when the key is missing. ages["Zed"] would raise KeyError; get("Zed") with no default gives None.
03What does len({"cat", "dog", "cat"}) give?
A set keeps each value once. The second "cat" is already a member, so it is dropped quietly and the set has 2 members.
04ages = {"Ana": 31}. What does 31 in ages give?
in on a dict checks the keys, not the values. "Ana" in ages is True; 31 in ages is False. Use 31 in ages.values() to check values.
05Why can a dict find a key quickly, even when it holds millions of pairs?
Dicts and sets use each key's hash value to work out where it lives, so a lookup goes straight there instead of searching. That is also why keys must be hashable.
Glossary
- Dictionary (dict)
- A collection of key: value pairs, written in curly braces, such as {"Ana": 31}. You look values up by key.
- Key
- The name you look a value up by. Each key appears once in a dict and must be hashable (for example a str, int or tuple).
- Value
- What a key points to. Any object can be a value, and values may repeat.
- KeyError
- The error Python raises when you ask a dict for a key it does not have, such as ages["Zed"].
- get()
- A dict method, d.get(key, default), that returns the key's value or the default when the key is missing.
- Set
- An unordered collection of unique values, such as {"cat", "dog"}. An empty set is written set(), because {} is an empty dict.
- Hash
- A whole number that hash() works out from a value. Dicts and sets use it to decide where a key belongs, so they can find it without searching.
- Membership test (in)
- x in s gives True or False. On a dict it checks the keys; on a set, the members.
Notes and sources
- For text, hash() gives a different number each time Python starts (a safety measure), but inside one run the same key always gives the same number. The figure leaves the number out.
- Looking up a key in a dict, or testing x in a set, takes about the same time on average whether it holds ten items or ten million. Testing x in a list has to check the items one by one.
- 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'.
- Curly braces with nothing inside, {}, make an empty dict. An empty set is written set().
Quiz Unlocks after the last step.