More dictionaries
We ended last time by talking about a dictionary storing TODO lists for each user (this file can be found here:
@dataclass class TodoItem: deadline: date tags: list description: str done: bool ## doug's TODO list class_item = TodoItem(date(2020, 11, 11), ["school", "class"], "Prepare for CSCI 0111", False) avocado_item = TodoItem(date(2020, 11, 16), ["home", "consumption"], "Eat avocado", False) birthday_item = TodoItem(date(2020, 11, 20), ["home", "friends"], "Buy present for friend", False) ## kathi's TODO list tas_item = TodoItem(date(2020, 11, 20), ["school", "class"], "Hire TAs for CS18 ", False) todos = {"doug": [class_item, avocado_item, birthday_item], "kathi": [tas_item]} def most_todos(todos: dict) -> str: most = 0 user_most = "" for user in todos: todo_lst = todos[user] if len(todo_lst) > most: most = len(todo_lst) user_most = user return user
The most_todos
function returns the name of the user with the most TODO
items. When this function executes, what will the type of user
be? What will
the type of todo_lst
be?
Updating dictionaries
We can modify a dictionary:
>>> todo_list["monica"] = [] >>> todo_list["monica"] [] >>> todo_list["doug"] = [] # overwrites previous value! >>> todo_list["doug"] [] >>> del todo_list["kathi"] # delete a key and its corresponding value >>> "kathi" in todo_list False
Data design
We’ve now learned about several ways of representing data in Python:
- Lists are used when we want individual elements in a particular order
- Dataclasses are used to combine multiple elements (possibly of different types)
- Dictionaries are used when we want mappings between keys and values
Let’s say we’re writing software to organize a 5k race. Which of these structures could we use to represent a single participant? We’d want to track their name, age group, etc.
Each runner is assigned a bib number. What structure could we use so that we can access a runner’s information given their bib number?
We want to give prizes to runners who completed the race fastest. How should we store information about the order in which runners completed the race?