3.1 — Dictionaries & Nested Data

Store each record as a dictionary, and keep many of them in a list or a dictionary.

Why This Matters

A list tells you the position of something. A dictionary tells you the name. Your app needs both: each item has a name, a quantity and a price, and you need to look things up by name.

The Idea

One record, as a dictionary:

apple = {"name": "Apple", "qty": 4, "price": 0.50}
print(apple["qty"])                    # 4
apple["qty"] = 3                       # change a value
print("price" in apple)                # True: is this key there?
print(apple.get("colour", "not set"))  # a default if the key is missing

Use [ ] when you know the key is there. Use .get() when it might not be.

A list of records:

items = [
    {"name": "Apple", "qty": 4, "price": 0.50},
    {"name": "Bread", "qty": 1, "price": 2.25},
]
for item in items:
    print(item["name"], item["qty"])

A dictionary of records, looked up by a key:

inventory = {
    "apple": {"qty": 4, "price": 0.50},
    "bread": {"qty": 1, "price": 2.25},
}
print(inventory["bread"]["price"])     # 2.25
for name, details in inventory.items():
    print(name, details["qty"])

Which one? If you look records up by name (a gradebook by student name), use a dictionary of records. If you keep an ordered list (a leaderboard sorted by score), use a list of records. Either is fine. Say which one you chose and why in your data sketch.

Try It

  1. Make a dictionary for one record from your app. Print one of its values.
  2. Change that value and print it again.
  3. Make a list of three records and loop over it, printing each name.
  4. Look up a key that doesn't exist. Read the KeyError, then fix it with .get().

Practice Notebook

Work through more examples, in different contexts, in a Jupyter notebook. Every exercise has a check cell that tells you when your code is right.

Download the notebook (3.1)

How to open it: open the file in VS Code, pick a Python kernel, and run the cells from top to bottom with Shift + Enter.

Common Mistakes

  • KeyError: the key isn't there. Check the spelling, or print data.keys() to see what's really in it.
  • Two records with the same key overwrite each other without any error. Decide what the key is before you start.
  • Changing a dictionary while you loop over it can break the loop. Make a list of the keys first, then loop over that list.

You're Done With This Lesson When…

You can make a dictionary, change a value, look one up safely, and loop over a list of records or a dictionary of records.