Chapter Six · Finding Things by Name

Dictionaries and Friends

Lists find things by position, but most real questions are asked by name. This chapter introduces the dictionary, which stores values under keys, together with two smaller relatives, the tuple and the set, and the nested shape that real data usually arrives in. It ends with the one behaviour of lists that surprises everybody once.

"What is the third item?" is a question lists answer well. "How much went on food?" and "What is Anna's number?" are not. Those are questions by name, and Python's answer to them is the dictionary. It turns out to be the most-used data structure in Python after the list, and the shape of almost everything that arrives from files and the internet.

Five topics. Dictionaries themselves, with a first real use: totalling spending by category. Walking through a dictionary safely, including what happens when a key is missing. Tuples and sets, two small tools with one clear job each. Lists of dictionaries, the shape real data comes in. And the surprise that the label picture from Chapter 2 was preparing you for: two names pointing at one list.

Four ways to hold several values
ContainerWritten asKeeps order?Can change?Find items by
list[1, 2, 3]yesyesposition
dictionary{"a": 1}yes, as addedyeskey
tuple(1, 2)yesnoposition
set{1, 2, 3}noyesmembership only

Topics in This Chapter