Dictionaries
Key and value, get, looping over items.
A dictionary stores "key and value" pairs and finds a value by its key quickly. It is written in curly braces:
prices = {"tea": 45, "coffee": 120}
print(prices["tea"]) # 45
prices["juice"] = 90
prices["tea"] = 50
del prices["coffee"]
print(prices) # {'tea': 50, 'juice': 90}
Keys are unique: writing to an existing key replaces the value. A key can be any immutable value: a string, a number, a tuple. A list cannot be a key. A dictionary remembers the order in which keys were added.
Accessing a missing key with [] raises KeyError. If a missing key is a normal situation, use get:
print(prices.get("milk")) # None
print(prices.get("milk", 0)) # 0
key in prices checks for the key, not the value. len(prices) returns the number of pairs.
The most convenient way to loop over a dictionary is items(), which gives pairs:
for name, price in prices.items():
print(name, price)
keys() and values() give only the keys or only the values. A common task is counting: counts[word] = counts.get(word, 0) + 1. get with a default value fits this best. In the standard library module there is an even shorter way, with Counter.
You cannot add or remove keys while looping over the same dictionary: Python stops with RuntimeError. Collect the keys into a list first, then delete.
Practice
A default value
What does the program print?
d = {"a": 1} print(d.get("b", 0))No such key
What happens when you access d["missing"] and the dictionary has no such key?
- KeyError
- None is returned
- An empty string is returned
- The key is created with the value None
Word counter
Write a function word_count(text) that returns a dictionary where the key is a word in lowercase and the value is how many times it occurred. Words are separated by spaces, and the keys go in the order of first appearance.