Dictionaries as records
A dictionary is a good way to keep the facts about one thing together, each under a name of its own:
person = {"name": "Ada", "age": 36, "city": "London"}
print(person["name"], "is", person["age"])
person["age"] += 1
print(person)
Ada is 36
{'name': 'Ada', 'age': 37, 'city': 'London'}Compare it with a list record, as earlier in this part: ["Ada", 36, "London"]. With the list, you have to remember that index 1 is the age. With the dictionary, the key says it: person["age"]. A record can also get new facts later, person["email"] = "ada@example.com", without moving anything that's already in it. The keys are strings like any other, so spell them the same way every time: person["Age"] would stop with a KeyError.
A list of records
A list of such dictionaries, all with the same keys, is a small database:
books = [
{"title": "The Glass Garden", "author": "Mia Stone", "pages": 312},
{"title": "Night Trains", "author": "Leo Grant", "pages": 205},
{"title": "Paper Moons", "author": "Mia Stone", "pages": 260},
]
for book in books:
print(f"{book['title']} by {book['author']}")
total = 0
for book in books:
total += book["pages"]
print("Average length:", total / len(books))
The Glass Garden by Mia Stone
Night Trains by Leo Grant
Paper Moons by Mia Stone
Average length: 259.0On each round, book is one dictionary, and book["title"] is its title. Inside an f-string that is itself in double quotes, write the key in single quotes, book['title'].
Functions make such a database easy to use. This one searches it and returns a new list of the matching titles:
def short_books(books: list, max_pages: int) -> list:
titles = []
for book in books:
if book["pages"] <= max_pages:
titles.append(book["title"])
return titles
books = [
{"title": "The Glass Garden", "author": "Mia Stone", "pages": 312},
{"title": "Night Trains", "author": "Leo Grant", "pages": 205},
{"title": "Paper Moons", "author": "Mia Stone", "pages": 260},
]
print(short_books(books, 300))
['Night Trains', 'Paper Moons']