Lists of Dictionaries
One dictionary describes one thing. When you have many things of the same kind, put their dictionaries in a list. Lists of dictionaries are everywhere in programming: products in an online shop, messages in a chat, students in a class.
movies = [
{"title": "Up", "year": 2009, "minutes": 96},
{"title": "Coco", "year": 2017, "minutes": 105},
{"title": "Shrek", "year": 2001, "minutes": 90}
]
print(movies[1])
print(movies[1]["title"]){'title': 'Coco', 'year': 2017, 'minutes': 105}
CocoEach element of the list is one dictionary, and the dictionaries are separated by commas like any other elements. To get to one value, first pick the element by its index, then the value by its key. Read movies[1]["title"] from left to right: from movies, take the element at index 1 (Coco's dictionary), and from it the value of "title".
Everything you know about lists still works: len(movies) is the number of movies, .append() adds a new one at the end, and you can change a value in one of them, for example movies[0]["minutes"] = 95.
Most often, you go through such a list with a for loop. In each iteration, the loop variable holds one whole dictionary:
for movie in movies:
print(f"{movie['title']} ({movie['year']})")Up (2009)
Coco (2017)
Shrek (2001)It's a good habit to name the list in the plural and the loop variable in the singular (movies, movie). The code then reads almost like a sentence: for each movie in movies.
The patterns from the lesson on loops work here too, for example adding up or picking with if:
total = 0
for movie in movies:
total += movie["minutes"]
if movie["year"] > 2005:
print("New:", movie["title"])
print("Minutes in total:", total)New: Up
New: Coco
Minutes in total: 291Typical mistakes:
movies["title"]: the list itself has no title, only the movies in it do. A list wants an index in square brackets, so the program ends withTypeError: list indices must be integers or slices, not str. Pick a movie first:movies[0]["title"].total += movieinstead oftotal += movie["minutes"]tries to add the whole dictionary to a number:TypeError: unsupported operand type(s) for +=: 'int' and 'dict'.
Instructions
Print whether the third task, “Learn Python”, is done: print the value of its key "done". The output should be False.
Below, write a for loop that prints the name of every task, each on its own line.
Finally, print To do: and below it the names of the tasks that aren't done yet. Tip: the value of "done" is already True or False, so you can use it in the condition directly: if not task["done"]:.
Start programming for free
7/9