Give a value a name you can look up.
Use a dictionary to keep related details in one small record.
A label can be more useful than a position.
Suppose you are describing a book. A list containing a title, a page count, and a reading status requires you to remember which position means what. A dictionary lets you attach a key to each value.
In the example, title and pages are keys. The values are “Small Adventures” and 96. Square brackets look up a value using its key. The quotation marks matter: "title" is text, while title without quotes would be a variable name.
A named lookup
title → Small Adventures pages → 96
author → Not listed
Decide what should happen when a detail is absent.
Looking up a missing key with square brackets raises a KeyError. For optional details, get() lets you provide a fallback. Here, an absent author becomes “Not listed” instead of stopping the program.
Choose a fallback that tells the truth. “Not listed” means this record does not contain the detail; it does not mean the book has no author. Small wording choices help your program preserve the difference between absent data and a real value.
book = {"title": "Small Adventures", "pages": 96}
print(book["title"])
print(book.get("author", "Not listed"))Make it yours.
- Run the example and read the two lines.
- Add an author key with a fictional name.
- Run it again and notice which output changes.
What changed when you tried it?
A little nudge
Place a comma between key-value pairs inside the braces.
What to look for
The first run prints Small Adventures and Not listed. After adding author, the second line contains your chosen name.
Take it one small step further
Change the page count and print book["pages"].
Use named keys when the meaning matters more than the position.
Read more: Python · Dictionaries ↗
No submission needed. This one is just for you.