Dictionaries
A dictionary maps keys to values, like a real dictionary maps words to meanings:
stock = {"apple": 5, "pear": 2}
stock["apple"] # 5
stock["kiwi"] = 7 # add or update
stock.get("plum", 0) # 0: a safe lookup with a defaultfor name, qty in stock.items(): print(name, qty)
key in stock tests whether a key exists; key not in stock tests that it is missing. Before appending to a list stored in a dict, create [] for a missing key.
stock.items() gives key-value pairs in insertion order, so grouped lists can keep the original order.
See it run
ages = {"mo": 30, "li": 25}
ages["jo"] = 41
ages["mo"] = 31
for name in ages:
print(name)A dict maps keys to values. Same square-bracket assignment either adds or overwrites.
Practice dictionaries
Exercise 1
Use stock in the editor below.
- Add
"kiwi"with 7. - Sell 2 apples (subtract 2 from the apple count).
- Loop with
.items()and print each line asapple: 3.
Exercise 2
Count how often each word appears in words in the editor below. Build the dict counts (word to count) with a loop, then set top to the count for "the".
Exercise 3
Use pets in the editor below. The vet wants pets grouped by species. Build by_species so each species maps to a list of pet names, in the order they appear in pets:
{"dog": ["Rex", "Fido"], "cat": ["Tom", "Kit"], "parrot": ["Polly"]}
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.