Lesson 07 · Beginner · 19 min

Python Dictionaries

Store labelled values and look them up by name instead of by position.

key accessget defaultsitems and counting

Regulars say 'the usual', which means nothing to a list of positions and everything to a name. A dictionary turns 'oat latte' into a price without counting rows. What should happen when the name is not on the menu?

A dictionary maps keys to values. Use it when a record has named fields, such as a drink, price, and quantity. Keys are unique; assigning an existing key replaces its value. You will also count values safely and read nested records one level at a time.

Look up a key

Square brackets read a value by key. A missing key raises KeyError. The get(key, default) method returns a fallback instead of raising, which is useful for optional fields and counting.

order = {"drink": "latte", "price": 4.5}
print(order["drink"])
print(order.get("quantity", 1))
print(order.get("notes", "none"))

Key access and defaults

Iterate over items

keys(), values(), and items() expose different views. items() yields key-value pairs that can be unpacked in a for loop. Insertion order is preserved in modern Python.

order = {"drink": "latte", "price": 4.5}
for key, value in order.items():
    print(key, value)

A record as a loop

Count with get

To count values, read the current count with get(name, 0), add one, and assign it back. This pattern handles the first occurrence without a separate check.

orders = ["latte", "tea", "latte"]
counts = {}
for drink in orders:
    counts[drink] = counts.get(drink, 0) + 1
print(counts)

Counting repeated values

Count without KeyError

counts[key] += 1 fails the first time a key appears. dict.get(key, 0) supplies a default without changing the dictionary. collections.Counter is the standard-library shortcut, but writing the loop once makes the counting rule visible.

votes = ["tea", "latte", "tea", "mocha", "tea"]
counts = {}
for vote in votes:
    counts[vote] = counts.get(vote, 0) + 1
print(counts)
print(counts.get("water", 0))

A default value makes counting safe

Read nested records one level at a time

Nested dictionaries are convenient and fragile: every level can be missing. Read one level at a time, use .get() for optional fields, and check the type before indexing. A missing customer is different from a customer with no name.

order = {"id": 7, "customer": {"name": "Maya"}, "items": ["latte"]}
customer = order.get("customer", {})
print(customer.get("name", "unknown"))
print(order.get("note", "no note"))
items = order.get("items", [])
print(isinstance(items, list), len(items))

Optional keys and type checks

Count with get()

dict.get(key, default) reads a missing key without raising KeyError, which makes counting compact. counts[word] = counts.get(word, 0) + 1 is the standard pattern. To rank results, sort items by value descending and key ascending; a lambda can return a tuple that describes both rules.

words = ["tea", "latte", "tea", "mocha", "tea"]
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
print(counts)
print(sorted(counts.items(), key=lambda pair: (-pair[1], pair[0])))

Count first, rank second

Key points

  • Dictionaries use named keys, not numeric positions.
  • get returns a default when the key is missing.
  • items() gives both key and value in one loop.
  • Assigning an existing key updates its value.
  • dict.get() supplies a default; nested access still needs checks.
  • get(key, 0) makes counting safe without a separate membership test.

Common mistakes

  • Using a missing key with square brackets and raising KeyError.
  • Forgetting that dictionary keys must be unique.
  • Trying to sort a dictionary directly instead of its items.
  • Using d[key] on optional data instead of d.get(key, default).
  • Using counts[word] += 1 before the key exists.
Your turn

Create an order dictionary, add a quantity field, and print a formatted total.

Try it yourself

Change the values, predict the output, then run the code. The Python runtime is downloaded the first time you press Run, so the first run can take a few seconds.

In-browser PythonRuns locally · no account
First run downloads Pyodide from a CDN. Use Run code after editing.

Practice this lesson

12 questions with immediate explanations.

See all 12 answersStart practice
← ListsFunctions →