Dictionaries That Hold Lists, Sets and Tuples
A dictionary value can be a list, a set or a tuple. Read it by its key, then use it like any other list, set or tuple.
Before this lesson you should know Dictionaries and Sets and Tuples.
A dictionary of lists
bags["Kofi"] is the list stored under "Kofi". Calling .append() on it
changes that list, inside the dictionary:
bags = {"Ada": ["rope"], "Kofi": []}bags["Kofi"].append("map")bags["Ada"].append("lamp")print(bags)It printed {'Ada': ['rope', 'lamp'], 'Kofi': ['map']}. Nothing is assigned
back to bags["Kofi"]: the list it holds has changed.
A dictionary of sets
Start each set at set(). pets["Mia"].add("cat") adds to the set stored
under "Mia", and a value added twice is still stored once:
pets = {"Mia": set(), "Tom": set()}pets["Mia"].add("cat")pets["Tom"].add("dog")pets["Mia"].add("cat")pets["Mia"].add("fish")print(sorted(pets["Mia"]))print(len(pets["Tom"]))It printed ['cat', 'fish'], then 1.
Note: do not write pets["Mia"] = pets["Mia"].add("cat"). add() changes
the set and gives back None, so the set would be lost.
Compare two sets from a dictionary
Each pets[name] is a whole set, so set operators work on it:
pets = {"Mia": {"cat", "fish"}, "Tom": {"dog", "fish"}}print(sorted(pets["Mia"] & pets["Tom"]))It printed ['fish'], the pet they both have.
A tuple as a value
A tuple cannot change, so to change a tuple value, store a new tuple under the key. Unpack it to read its parts:
places = {"Ada": (0, 1), "Kofi": (2, 0)}places["Ada"] = (1, 1)row, col = places["Ada"]print(row)print(col)It printed 1, then 1: Ada's place is now (1, 1).
See also: Nested Data, Python Set Operations.
Your turn
Add three lines: add "owl" to Tom's set, add "bat" to it, then print Tom's
set in sorted order.
['bat', 'owl']
pets = {"Mia": set(), "Tom": set()}pets["Mia"].add("cat")# add "owl" and "bat" to Tom's set, then print it sorted (three lines)