SyntaxPilot
Courses/Python/Lesson 12
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Python · Lesson 12 of 40

Dictionaries

queued

These are the notes for Python episode 12. Lists find things by position: item 0, item 1. Real life finds things by name: the price of samosa, Asha's phone number, the marks of roll number 12. Searching a list for a price is clumsy, and two parallel lists silently drift apart, so we invent the dictionary. You will learn keys and values, reading with [] and KeyError, safe reading with .get(), adding, updating and deleting, unique keys, looping with keys(), values() and items(), the counting pattern, why a list can't be a key, and lists as values. Every example below runs as-is in the SyntaxPilot compiler, with its real output from Python 3.13.

The problem: finding a price

Last episode the menu became a list of tuples. To find one price, the program walks through the list:

menu = [("Chai", 10), ("Samosa", 15), ("Vada pav", 20)]

for item, price in menu:
    if item == "Samosa":
        print("Samosa:", price)

Output:

Samosa: 15

It works, but every lookup is a whole loop that checks pairs one by one. Another idea, two lists in the same order:

names = ["Chai", "Samosa", "Vada pav"]
prices = [10, 15, 20]
print("Samosa:", prices[names.index("Samosa")])

names.remove("Samosa")
print("Vada pav:", prices[names.index("Vada pav")])

Output:

Samosa: 15
Vada pav: 15

Vada pav costs ₹20, not ₹15. Why: we removed "Samosa" from names but not from prices, so every name after it shifted by one. Two lists tied together only by position (parallel lists) drift apart silently.

The dictionary: keys and values

In your phone In Python
You search by the contact name: Asha the key: "Samosa"
You get what's saved with it: her number the value: 15
Type a name, get the number, no scrolling menu["Samosa"] → 15, instantly

A dictionary (dict) stores key: value pairs in curly brackets. You look up a value by its key. Each key and its value are stored together, so they can never drift apart.

menu = {"Chai": 10, "Samosa": 15, "Vada pav": 20}
print(menu)
print(menu["Samosa"])
print(len(menu))
print("Chai" in menu)

Output:

{'Chai': 10, 'Samosa': 15, 'Vada pav': 20}
15
3
True
  • menu["Samosa"]: key in square brackets, value out.
  • len(menu): the number of key-value pairs.
  • "Chai" in menu: in checks the keys, and it's instant (dictionaries use hashes, like sets).

KeyError and .get()

menu = {"Chai": 10, "Samosa": 15, "Vada pav": 20}
print(menu["Pizza"])

Output:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(menu["Pizza"])
          ~~~~^^^^^^^^^
KeyError: 'Pizza'

Square brackets with a missing key raise KeyError (the dictionary's version of IndexError). Keys are also case-sensitive: "chai" and "Chai" are different keys. The safe way is .get():

menu = {"Chai": 10, "Samosa": 15, "Vada pav": 20}
print(menu.get("Pizza"))
print(menu.get("Pizza", "not on the menu"))

Output:

None
not on the menu

d.get(key) returns None if the key is missing; d.get(key, default) returns your default.

Add, update, delete

menu = {"Chai": 10, "Samosa": 15, "Vada pav": 20}
menu["Lassi"] = 25
menu["Chai"] = 12
del menu["Samosa"]
print(menu)

Output:

{'Chai': 12, 'Vada pav': 20, 'Lassi': 25}
  • d[key] = value adds the pair if the key is new, and updates the value if it exists.
  • del d[key] deletes the pair (a missing key is a KeyError).
  • Dictionaries remember the order keys were added (since Python 3.7).
  • Deleting "Samosa" deleted its price too: the parallel-lists bug can't happen.

More methods:

menu = {"Chai": 10, "Samosa": 15}
print(list(menu.keys()), list(menu.items()))
price = menu.pop("Samosa")
print(price, menu)
menu.update({"Lassi": 25, "Chai": 12})
print(menu)

Output:

['Chai', 'Samosa'] [('Chai', 10), ('Samosa', 15)]
15 {'Chai': 10}
{'Chai': 12, 'Lassi': 25}

pop(key) removes a pair and returns its value; update(other) adds or overwrites many pairs at once.

Keys are unique

menu = {"Chai": 10, "Chai": 12}
print(menu)

Output:

{'Chai': 12}

No error: the second "Chai" overwrote the first. A key appears only once, like a contact name. Values can repeat.

Looping: keys, values, items

menu = {"Chai": 10, "Samosa": 15, "Vada pav": 20}
for item in menu:
    print(item)
print(list(menu.values()))

for item, price in menu.items():
    print(f"{item:10} Rs {price}")

Output:

Chai
Samosa
Vada pav
[10, 15, 20]
Chai       Rs 10
Samosa     Rs 15
Vada pav   Rs 20
Loop Gives you
for k in d: (or d.keys()) each key
for v in d.values(): each value
for k, v in d.items(): each (key, value) tuple, unpacked

Don't add or delete keys while looping over the same dictionary:

menu = {"Chai": 10, "Samosa": 15}
for item in menu:
    if item == "Chai":
        del menu[item]

Output:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    for item in menu:
                ^^^^
RuntimeError: dictionary changed size during iteration

Build a new dictionary instead (see practice 4), or loop over list(menu).

Counting with a dictionary

Raju wants to know what sells the most. On paper you'd write each item once and make tally marks: item → count, which is a dictionary. The obvious code:

orders = ["chai", "samosa", "chai", "chai", "lassi", "samosa"]
counts = {}
for o in orders:
    counts[o] += 1
print(counts)

Output:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    counts[o] += 1
    ~~~~~~^^^
KeyError: 'chai'

The first "chai" isn't in the dictionary yet, so there's no number to add 1 to. The fix:

orders = ["chai", "samosa", "chai", "chai", "lassi", "samosa"]
counts = {}
for o in orders:
    counts[o] = counts.get(o, 0) + 1
print(counts)

Output:

{'chai': 3, 'samosa': 2, 'lassi': 1}

counts.get(o, 0) is the current count, or 0 for a new item. This counting pattern (also called a frequency count) is everywhere: words in a text, votes, letters in a string, and it's an interview favourite.

What can be a key?

seats = {["B", 4]: "Asha"}

Output:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    seats = {["B", 4]: "Asha"}
            ^^^^^^^^^^^^^^^^^^
TypeError: unhashable type: 'list'

A dictionary files each key by its hash, a code computed from the key's value. If a key could change, its hash would change and the entry would be lost. So keys must be immutable: strings, numbers, and tuples work; lists, sets and dictionaries don't. Hashable means "has a hash that never changes".

seats = {("B", 4): "Asha"}
print(seats[("B", 4)])

Output:

Asha

Values can be anything, even lists:

marks = {"Asha": [85, 92], "Ravi": [70, 64]}
marks["Asha"].append(78)
print(marks["Asha"])

for name, m in marks.items():
    print(name, sum(m) / len(m))

Output:

[85, 92, 78]
Asha 85.0
Ravi 67.0

Common mistakes

Mistake What you see Why Fix
parallel names / prices lists no error, the wrong price the lists drift apart one dict {name: price}
menu["Pizza"] KeyError: 'Pizza' the key doesn't exist menu.get("Pizza", default) or check in
menu["chai"] when the key is "Chai" KeyError: 'chai' keys are case-sensitive use one spelling (e.g. all lowercase)
counts[o] += 1 for a new key KeyError: 'chai' nothing to add 1 to yet counts[o] = counts.get(o, 0) + 1
{"Chai": 10, "Chai": 12} no error, one key keys are unique; last wins use different keys
{["B", 4]: "Asha"} TypeError: unhashable type: 'list' keys must be immutable ("B", 4)
deleting keys while looping RuntimeError: dictionary changed size during iteration the loop's dict changed under it build a new dict
empty = {} for a set no error, it's a dict {} is an empty dict set()

Mini project: the billing counter

The menu is a dictionary of item → price; the order is a list. Print each line of the bill and the total, and handle items that aren't on the menu without crashing.

# Mini project: billing counter
menu = {"chai": 10, "samosa": 15, "vada pav": 20, "lassi": 25}
order = ["chai", "samosa", "chai", "pizza", "lassi"]

total = 0
for item in order:
    if item in menu:
        print(f"{item:10} Rs {menu[item]}")
        total += menu[item]
    else:
        print(f"{item:10} not on the menu")
print("Total: Rs", total)

Output:

chai       Rs 10
samosa     Rs 15
chai       Rs 10
pizza      not on the menu
lassi      Rs 25
Total: Rs 60

Extend it: make the order a dictionary of item → quantity.

Solution
menu = {"chai": 10, "samosa": 15, "vada pav": 20}
order = {"chai": 2, "samosa": 3}
total = 0
for item, qty in order.items():
    cost = menu[item] * qty
    print(f"{item:8} x{qty}  Rs {cost}")
    total += cost
print("Total: Rs", total)

Output:

chai     x2  Rs 20
samosa   x3  Rs 45
Total: Rs 65

Practice

1. A phonebook: add two names, look one up safely, delete one, and look it up again.

Solution
phone = {}
phone["Asha"] = "98100 11111"
phone["Ravi"] = "98100 22222"
print(phone.get("Asha", "not found"))
del phone["Ravi"]
print(phone.get("Ravi", "not found"))
print(phone)

Output:

98100 11111
not found
{'Asha': '98100 11111'}

2. Count each letter in a word.

Solution
word = "banana"
counts = {}
for ch in word:
    counts[ch] = counts.get(ch, 0) + 1
print(counts)

Output:

{'b': 1, 'a': 3, 'n': 2}

3. Find the item with the highest count, two ways.

Solution
counts = {"chai": 3, "samosa": 2, "lassi": 1}
best = max(counts, key=counts.get)
print(best, counts[best])
best_item = ""
best_count = 0
for item, c in counts.items():
    if c > best_count:
        best_item, best_count = item, c
print(best_item, best_count)

Output:

chai 3
chai 3

max(counts, key=counts.get) compares the keys by their values. We'll see key= properly in the lambda episode.

4. Build a new dictionary of the items that cost ₹15 or less.

Solution
cheap = {}
menu = {"chai": 10, "samosa": 15, "vada pav": 20, "lassi": 25}
for item, price in menu.items():
    if price <= 15:
        cheap[item] = price
print(cheap)

Output:

{'chai': 10, 'samosa': 15}

Quick quiz

d = {"a": 1}
d["a"] = 5
d["b"] = 2
print(len(d))

What does it print? 3, 2, 1, or KeyError?

Answer

2. d["a"] = 5 updates the existing key; d["b"] = 2 adds a new one.

Interview questions

  1. What is a dictionary? A mapping of unique, hashable keys to values, with fast lookup by key.
  2. d[key] vs d.get(key)? d[key] raises KeyError if the key is missing; d.get(key, default) returns None or the default.
  3. Why can't a list be a dictionary key? Keys must be hashable (their hash must never change); lists are mutable, so they're unhashable. Use a tuple.
  4. How do you count occurrences with a dictionary? d[x] = d.get(x, 0) + 1 in a loop (or collections.Counter, covered in the standard library episode).
  5. Are dictionaries ordered? Since Python 3.7, they keep insertion order.
  6. How fast is a lookup? On average constant time, O(1): it doesn't depend on the number of keys, unlike searching a list, which is O(n).
  7. What happens with duplicate keys in a literal? The last value wins: {"a": 1, "a": 2} is {"a": 2}.

Glossary

Term Meaning Example
Dictionary (dict) A collection of key: value pairs, looked up by key {"Chai": 10}
Key What you look up by; unique and immutable "Samosa"
Value What's stored with a key; can be anything 15
Key-value pair One key with its value "Chai": 10
Parallel lists Two lists linked only by position names and prices
KeyError Reading or deleting a key that isn't there menu["Pizza"]
.get(k, default) Read a value safely, with a fallback menu.get("Pizza", 0)
del d[k] / .pop(k) Delete a pair / delete and return the value del menu["Samosa"]
.update(other) Add or overwrite many pairs menu.update({"Lassi": 25})
.keys() / .values() / .items() The keys / values / (key, value) pairs for k, v in menu.items():
Insertion order Dicts keep keys in the order they were added Lassi at the end
Counting pattern d[x] = d.get(x, 0) + 1 in a loop order counts
Hash A code computed from a value, used to file and find keys fast why lookups are instant
Hashable Has a hash that never changes; required for keys strings, numbers, tuples
Unhashable Can change, so can't be a key lists, sets, dicts
Case-sensitive "chai" and "Chai" are different keys

Summary

  • A dictionary maps keys to values: menu = {"Chai": 10, "Samosa": 15}; look up with menu["Samosa"].
  • A missing key with [] is a KeyError; .get(key, default) is the safe read.
  • d[k] = v adds or updates; del d[k] deletes; keys are unique.
  • Loop with keys(), values(), items().
  • Count with d[x] = d.get(x, 0) + 1.
  • Keys must be immutable (a tuple works, a list is unhashable); values can be anything.

Next episode: functions. The billing code works for one order; for hundreds of orders, we stop copy-pasting and write a function.