Lists and Dictionaries
Dictionaries and their keys
Look a value up in a dictionary by its key, and work out what adding a key or writing over one leaves behind.
A list is the right thing to reach for when what you have is a run of values in an order — readings taken one after another, marks down a column. It is the wrong thing when what you have is values that belong to names: how many of each item a shop holds, or how many people answered each of four questions. Position 2 means nothing there, and remembering that position 2 is the one for pencils is exactly the kind of thing programs are meant to save you from. A dictionary stores pairs instead. Each pair is a key and a value, written with a colon between them and commas between the pairs, and the key — not a position — is what you look a value up by. A dictionary can only answer for a key it was actually given; ask it for one it has never met and the program stops rather than inventing an answer.
Same square brackets, two different questions
A list and a dictionary are both looked in with square brackets, and what goes inside them is the whole difference. With a list, what goes in is a position — a number, decided by where the value sits, and only ever between 0 and one less than the length. With a dictionary, what goes in is a key — chosen by whoever wrote the program, usually a word, and meaningful in itself. So a dictionary has no first pair or third pair worth naming, and no length you have to stay inside: there is only whether it has the key you are asking about.
Worked example
Which key holds the largest value in this dictionary?
tally = {"north": 18, "south": 41, "east": 7, "west": 23}Ignore the keys for a moment and look only at the values: 18, 41, 7 and 23. The largest of them is 41.
The keys cannot help with this part. Nothing about the word south makes its number bigger, which is the point of keys being names rather than places.
Try it together
Now follow one dictionary through three changes.
stock = {"pen": 8, "book": 3}
stock["bag"] = 5
stock["pen"] = stock["pen"] + 4
stock["book"] = 10All three lines are written the same way. What each one does depends entirely on whether its key was already there.
1.Only one of the three lines makes the dictionary bigger. Which key does that line add?
Have a go
Have a go on your own. What does this program print?
seen = {"cup": 1}
seen["cup"] = seen["cup"] + 6
seen["box"] = 2
print(len(seen))Ready to practise?
Eight questions on what you have just read. Nothing is timed, and you can play as many times as you like.