Dictionaries: Looking Things Up by Name
About 18 minutes
Why this matters
A list finds things by position. A dictionary finds them by name: a phone book that goes from a person to a number, a menu that goes from a dish to a price. It is one of the most useful tools in Python, and it is very fast, even with a million entries.
The idea
ages = {"Ada": 36, "Bo": 41} # key: value pairs
print(ages["Ada"]) # 36
ages["Cy"] = 29 # add a new pair
ages["Bo"] = 42 # change an existing one
print("Bo" in ages) # True (checks the keys)
print(len(ages)) # 3
for name in ages: # loops over the keys
print(name, ages[name])
for name, age in ages.items(): # keys and values together
print(name, age)
Asking for a key that is not there is a KeyError. .get(key, default) gives a fallback instead:
print(ages.get("Zed", 0)) # 0
That unlocks the classic counting pattern:
counts = {}
for letter in "banana":
counts[letter] = counts.get(letter, 0) + 1
print(counts) # {'b': 1, 'a': 3, 'n': 2}
Keys must be unchangeable values like text, numbers or tuples. Dictionaries remember the order in which keys were added.
Try it
Count the letters in your own name using the pattern above. Which letter appears most?
Your turn
The starter reads a sentence. Count how many times each word appears, ignoring capital letters, and print the words in alphabetical order, then the number of different words:
the: 2
cat: 1
For The cat the the output is:
cat: 1
the: 2
Unique words: 2
Recap
{key: value}maps keys to values; read and write withd[key]..get(key, default)avoidsKeyError, which makes counting easy.- Loop with
for key in d, orfor key, value in d.items(); usesorted(d)for alphabetical order.
Common mistakes
KeyErrorfrom reading a key that is missing. Use.get()or check within.- Looking up by value. Dictionaries are fast one way only: key to value.
- Forgetting
.lower(), so “The” and “the” count separately.