Byte by Byte › Book 7: Networks, Programming and Machine Learning › Chapter 7: Dictionaries and Program Design
Chapter 7: Dictionaries and Program Design
You will learn: how dictionaries store data as key–value pairs, how to add, change, look up and remove entries safely, how to loop through a dictionary, how to count things with a dictionary, lists of dictionaries as simple records, how to design a larger program top-down with a structure chart, how to read a traceback, the three kinds of error, and how to debug with print statements and the IDLE debugger.
🔎 The Case
Beautine had found the account profiles. Every account on the Memunic message boards had one, and she had copied all forty of the suspicious ones into her records, which was against no rule she knew of, and she had checked.
Each profile was a little bundle of facts: the account's name, the village it claimed to be from, the date it was created, how many followers it had, how many posts it had made, and which accounts it followed.
Memoon tried to store them the way she knew. One list for names. One list for villages. One for dates. One for followers. Six lists, each forty items long, and item 17 in every list had to belong to the same account. When she sorted one list to find the newest accounts, the other five stayed in the old order, and suddenly every account had someone else's date.
She put her head on the desk.
"When you look up a word in Kachui's dictionary," said Nimo, "you don't count to the four-thousandth word. You look up the word itself, and everything about it is right there."
"I know how a dictionary works, Nimo."
"Python has them too," said Nimo, pleased with himself. "And so far you've only been using half of Python."
💡 The Concepts
What is a dictionary? A dictionary stores data as key–value pairs. Each key is a label you use to look something up; each value is the data stored under that label. You write a dictionary in curly brackets, with a colon between each key and its value.
account = {
"name": "echo_4471",
"village": "Moonbrook",
"created": "2026-09-30",
"followers": 3,
"posts": 61,
}
A list finds data by position ( villages[2] ). A dictionary finds data by key ( account["village"] ). This makes dictionaries perfect for anything with named parts, such as a profile, a record or a settings file.
Rules for dictionaries:
- Keys must be unique: if you use the same key twice, the second value replaces the first.
- Keys are usually strings or numbers, and must be immutable (so a list cannot be a key).
- Values can be anything: numbers, strings, lists, even other dictionaries.
- Dictionaries are mutable, like lists.
- Since Python 3.7, a dictionary remembers the order in which keys were added.
Using a dictionary.
| Code | What it does |
|---|
account["village"] Looks up a value (gives KeyError if the key does not
exist)
account.get("email") Looks up a value; gives None if the key does not exist
account.get("email", "not given") | Gives a default value instead of None |
account["followers"] = 4 | Changes an existing value |
account["flagged"] = True | Adds a new key–value pair |
del account["flagged"] | Removes a key and its value |
account.pop("posts") | Removes a key and returns its value |
"posts" in account True if the key exists (it checks keys, not values)
len(account) | Number of key–value pairs |
Notice that "Moonbrook" in account is False , even though Moonbrook is one of the values, because in checks keys.
Looping through a dictionary.
for key in account:
print(key)
for key, value in account.items():
print(f"{key}: {value}")
The methods .keys() , .values() and .items() give the keys, the values, and the (key, value) pairs. Wrap them in list() if you want an actual list: list(account.keys()) .
Counting with a dictionary. One of the most useful patterns in all of programming is counting how often each thing appears. Use each thing as a key and its count as the value.
text = "stop check share stop think check stop"
counts = {}
for word in text.split():
if word in counts:
counts[word] = counts[word] + 1
else:
counts[word] = 1
print(counts)
Output: {'stop': 3, 'check': 2, 'share': 1, 'think': 1} .
The if / else can be shortened with .get() : counts[word] = counts.get(word, 0) + 1 . If the word is new, .get() gives 0, so the count starts at 1.
To print the most common first, sort the keys by their values:
for word in sorted(counts, key=counts.get, reverse=True):
print(word, counts[word])
The key=counts.get argument tells sorted() to compare the words by looking up each one's count. Counting like this is how search engines find important words, how spam filters spot suspicious ones, and how the Chapter 3 frequency analysis really works.
Lists of dictionaries: records. A list in which every item is a dictionary with the same keys is a simple way to store a table of records, like the database tables you met in Book 6. Each dictionary is one record (a row); each key is a field (a column).
accounts = [
{"name": "echo_4471", "created": "2026-09-30", "followers": 3},
{"name": "luna_moonbrook", "created": "2019-04-11", "followers": 812},
{"name": "echo_0912", "created": "2026-09-30", "followers": 2},
]
for a in accounts:
if a["created"] >= "2026-09-01" and a["followers"] < 10:
print("New and tiny:", a["name"])
Output:
New and tiny: echo_4471 New and tiny: echo_0912
The fields can never get out of step, because each record keeps its own fields together. Dates written as YYYY-MM-DD compare correctly as text, for the same reason as the times in Chapter 5. A dictionary can also hold a list (an account's "follows" list) or another dictionary: this nesting is how most real data on the web is shaped.
Real World: When apps send data over the internet, they usually send it as JSON (JavaScript Object Notation), which looks almost exactly like Python dictionaries and lists. A weather app, a train-times app and a UPI payment confirmation all receive JSON. Python's built-in json module turns JSON text into dictionaries and back again.
Choosing a data structure.
| Use a... | When... | Example |
|---|---|---|
| Variable | You have one value | score = 95 |
| String | You have text | name = "Vega" |
| List | You have many values in an order | A list of posts in time order |
| Tuple | A fixed group of values that should not change | ("06:42", "echo_4471") |
| Dictionary | You look things up by name or label | One profile; word counts |
| List of dictionaries | Many records with the same fields | All forty profiles |
Designing bigger programs. As programs grow, the hard part is no longer writing lines; it is organising them. The standard approach is top-down design (also called stepwise refinement): start with the whole problem, break it into a few big tasks, then break each task into smaller ones, until every piece is small enough to be one function. This is decomposition (Book 5) applied to code.
A structure chart draws this as a tree. The whole program is at the top; each box below is a function; lines show which function calls which.
Account investigator
┌───────────────┼───────────────┐
load_profiles find_suspects print_report
┌────┴─────┐
is_new_account follows_count
Good program design follows a few habits:
- One function, one job. If you need the word and to describe it, split it.
- Meaningful names for variables and functions:
follower_count, notfc. - No magic numbers. Put fixed values in clearly named variables at the top, written in capitals by convention:
NEW_ACCOUNT_DATE = "2026-09-01". Change it once, and the whole program uses the new value. - Comments explain why, not what.
# accounts made after the attack began are suspicioushelps;# add 1 to xdoes not. - A
main()function that reads like a summary of the program, calling the other functions in order. - Test each function as you write it, not all at the end.
Three kinds of error.
| Kind | When it happens | Example | How you notice |
|---|
Syntax error Before the program runs: Missing colon after if ; Python refuses to run
| the code breaks Python's grammar rules | unclosed bracket | and highlights the spot |
Runtime error While running: an KeyError , The program crashes (exception) instruction is impossible IndexError , ZeroDivis with a traceback
ionError , ValueError
Logic error The program runs without Using < instead of <= ; Only by testing with
| crashing but gives the wrong answer | adding instead of multiplying | data you know the answer for |
Logic errors are the most dangerous, because nothing warns you. This is why testing (Chapter 6) matters.
Reading a traceback. When a runtime error happens, Python prints a traceback: a report of where the program was when it failed. Read it from the bottom up.
Traceback (most recent call last):
File "investigate.py", line 24, in <module>
main()
File "investigate.py", line 20, in main
print_report(suspects)
File "investigate.py", line 15, in print_report
print(a["village"], a["email"])
KeyError: 'email'
- The last line names the error and the detail: there is no key called
'email'. - The line above it shows the exact code that failed, and the line before that gives its file and line number (15) and the function it was in.
- The lines further up show how the program got there:
main()calledprint_report(), which failed. This chain of calls is the call stack.
The fix here: use a.get("email", "none") , or check if "email" in a: first.
Debugging. Debugging means finding and fixing errors. Good debuggers are calm and methodical, not lucky.
- Reproduce it: find an input that always causes the problem.
- Read the error message and traceback carefully.
- Trace the values: add temporary
print()lines showing variables at key points, or do a dry run with a trace table (Book 6). - Narrow it down: test each function on its own until you find the one giving the wrong result.
- Fix one thing at a time, then test again, including the tests that passed before.
- Rubber duck debugging: explain your code, line by line, out loud to someone, or even to a toy duck. Saying it often reveals the mistake.
The IDLE debugger. IDLE has a built-in debugger that runs your program one line at a time while showing every variable's value.
- In the Python Shell window (not the editor), click Debug → Debugger. A Debug Control window opens and the shell shows
[DEBUG ON]. - Go back to your program and press F5 to run it. It pauses on the first line.
- Click Step to run one line at a time, going into functions; Over runs a function call without stepping inside; Out finishes the current function; Go runs until the next breakpoint.
- Tick Locals and Globals to watch the variables change.
- To pause at a particular line, right-click it in the editor and choose Set Breakpoint (it turns yellow), then click Go.
- Click Debug → Debugger again in the shell to switch it off.
Stepping through a program and watching its variables is one of the fastest ways to understand code, including code someone else wrote.
Career Spotlight: Quality assurance (QA) engineer. QA engineers break software on purpose before customers do. They design tests for normal, boundary and invalid inputs, report bugs precisely enough for a developer to reproduce them, and check that fixes do not break anything else.

🛠️ Build It
Activity 1: Contact book. Save as contacts.py . It stores names as keys and phone numbers as values.
contacts = {}
while True:
choice = input("\n(a)dd, (f)ind, (l)ist, (d)elete, (q)uit: ").lower()
if choice == "a":
name = input("Name: ").strip().title()
contacts[name] = input("Number: ").strip()
elif choice == "f":
name = input("Name: ").strip().title()
print(contacts.get(name, "No such contact."))
elif choice == "l":
for name in sorted(contacts):
print(f"{name:<15}{contacts[name]}")
elif choice == "d":
name = input("Name: ").strip().title()
if name in contacts:
del contacts[name]
print("Deleted.")
else:
print("No such contact.")
elif choice == "q":
break
Use made-up names and numbers only. Improve it so that adding a name that already exists asks "Replace the old number? (y/n)".
Activity 2: Word counter. Write a program that asks for a paragraph, cleans it (lower case, and remove the punctuation .,!? with .replace() ), counts every word with a dictionary, and prints the five most common words with their counts. Try it on a paragraph from one of your school textbooks.
Activity 3: Text adventure. Save as adventure.py . The game's map is a dictionary of rooms; each room is itself a dictionary holding a description, its exits (another dictionary) and an item.
"""The Old Mill: a short text adventure."""
rooms = {
"yard": {
"description": "A snowy yard outside the old mill. A door leads
north.",
"exits": {"north": "hall"},
"item": None,
},
"hall": {
"description": "A dusty hall. Stairs go up; a cellar door leads
down.",
"exits": {"south": "yard", "up": "loft", "down": "cellar"},
"item": "lamp",
},
"loft": {
"description": "A loft full of burned paper. Someone left in a
hurry.",
"exits": {"down": "hall"},
"item": "note",
},
"cellar": {
"description": "A cold stone cellar, lit by your lamp.",
"exits": {"up": "hall"},
"item": "mirror shard",
},
}
def show_room(name, inventory):
"""Print the room's description, its item and its exits."""
room = rooms[name]
if name == "cellar" and "lamp" not in inventory:
print("It is too dark to see anything.")
else:
print(room["description"])
if room["item"] is not None:
print(f"You see a {room['item']}.")
print("Exits:", ", ".join(room["exits"]))
def move(current, direction):
"""Return the new room name, or the same room if there is no exit that
way."""
exits = rooms[current]["exits"]
if direction in exits:
return exits[direction]
print("You can't go that way.")
return current
def take(current, inventory):
"""Move the room's item into the inventory, if there is one."""
item = rooms[current]["item"]
if item is None:
print("There is nothing to take.")
elif current == "cellar" and "lamp" not in inventory:
print("You can't find anything in the dark.")
else:
inventory.append(item)
rooms[current]["item"] = None
print(f"You take the {item}.")
def main():
current = "yard"
inventory = []
print("THE OLD MILL. Commands: go <direction>, take, inventory, quit")
while True:
print()
show_room(current, inventory)
command = input("> ").strip().lower()
if command.startswith("go "):
current = move(current, command[3:])
elif command == "take":
take(current, inventory)
elif command == "inventory":
print("You carry:", inventory if inventory else "nothing")
elif command == "quit":
print("Goodbye.")
break
else:
print("I don't understand that.")
if "mirror shard" in inventory and "note" in inventory:
print("\nYou have the shard and the note. Case solved!")
break
if __name__ == "__main__":
main()
Play it. Then extend it: add two new rooms, a locked door that needs a key item, and a move counter that prints your total at the end. Draw a structure chart of your finished game first.
Why it works: move() never needs a long if chain for every direction, because each room's exits dictionary already says where each direction leads. Adding a room means adding data, not code. Separating data from the code that uses it is a mark of good design.
Activity 4: Debugging challenge. This program should print the average follower count of new accounts, but it has three bugs: one syntax error, one runtime error and one logic error. Find and fix all three, and say which is which.
accounts = [
{"name": "echo_4471", "created": "2026-09-30", "followers": 3},
{"name": "luna_moonbrook", "created": "2019-04-11", "followers": 812},
{"name": "echo_0912", "created": "2026-09-30", "followers": 2},
]
total = 0
new_count = 0
for a in accounts
if a["created"] >= "2026-09-01":
total = total + a["follower"]
new_count = new_count + 1
print("Average:", total / len(accounts))
Then set a breakpoint on the total = ... line and step through it with the IDLE debugger, watching total and new_count change. (The correct answer is 2.5.)
Unplugged: Human dictionary. Each person holds a card with a key on the front and a value on the back ( capital_of_kerala / Thiruvananthapuram ). Someone calls a key; the person holding it reads out the value. Then try in : call a key nobody holds. What should the caller do instead of crashing? (Answer: use a default, like .get() .) Finally, two people try to hold the same key. Why can't a dictionary allow that?
✅ Case Closed
With each profile stored as a dictionary, Memoon's investigator program was short and clear, with a structure chart pinned above the desk. load_profiles() read Beautine's records into a list of dictionaries. find_suspects() kept the accounts made recently with almost no followers. print_report() printed a neat table.
The report was stranger than anyone expected. All forty accounts had been created on the same day: 30 September, one week before the fake picture appeared. All forty claimed to be from different villages, but they had all been created through Moonbrook's market access point. And every one of them followed the same single account.
Memoon used a counting dictionary on the forty "follows" lists. One name came out on top, followed by forty out of forty.
the_looking_glass
Its profile was almost empty. No posts. No village. Just one line: Everything you see is a reflection.
"A mirror," said Simbha quietly. "The Mirror Engine."
Vega was already pulling up the Snowpeak hub's connection logs. "Every time an account logs in, the hub records where it connected from. If the_looking_glass ever logged in, even once, its address is in here." She scrolled. And scrolled. "Somewhere in here. In two million, four hundred thousand entries."
Memoon's first program checked them one by one. Ten minutes later it was still running, and Vega had started drumming her talons on the desk.
"There has to be a faster way to find one thing in a pile that big," said Memoon.
"There is," said Frost. "But first, the pile has to be in order."
❓ Test Yourself
- What is a dictionary? How is looking something up in a dictionary different from looking it up in a list?
- Write a dictionary describing yourself with at least four keys.
- For
pet = {"name": "Noodles", "type": "cat", "age": 6}, write code to: (a) print the name, (b) change the age to 7, (c) add a key"collar"with value"blue", (d) remove the type, (e) check whether the key"owner"exists. - What is the difference between
pet["owner"]andpet.get("owner")when the key does not exist? - What is printed?
print("cat" in {"type": "cat"}). Explain. - Write a loop that prints every key and value in
petin the formname = Noodles. - Complete this counting code so it counts each letter in a word:
counts = {}/for ch in "banana":/counts[ch] = - When would you use a list of dictionaries instead of one dictionary?
- Name the three kinds of error and give one example of each.
- In which direction should you read a traceback, and what does its last line tell you?
- What is top-down design? Draw a structure chart for a program that runs a class quiz: it loads questions, asks them, marks answers and shows a final score.
- Challenge: Write a program for a school library. Store each book as a dictionary with title, author, year and a
"borrowed"value ofTrueorFalse, in a list.
Write functions to: list all available books, search by author (any capitals), borrow a book by title, and return a book. Include a main() with a menu.
📚 Key Terms
- Dictionary: a mutable collection of key–value pairs, written in curly brackets.
- Key: the unique label used to look up a value in a dictionary.
- Value: the data stored under a key.
- Key–value pair: one key and its value.
.get(): a dictionary method that looks up a key safely, with an optional default..items(): a method that gives each (key, value) pair, for looping.- Record: one set of related fields, such as one profile; often a dictionary.
- Nesting: placing lists or dictionaries inside other lists or dictionaries.
- JSON: a standard text format for data, shaped like dictionaries and lists.
- Top-down design (stepwise refinement): breaking a problem into smaller and smaller tasks.
- Structure chart: a diagram showing how a program is split into functions.
- Magic number: an unexplained fixed value in code; better replaced by a named constant.
- Syntax error: code that breaks the rules of the language.
- Runtime error (exception): an error that happens while the program runs.
- Logic error: a mistake that makes a program give wrong results without crashing.
- Traceback: Python's report of where a runtime error happened.
- Call stack: the chain of function calls that led to the current line.
- Debugging: finding and fixing errors.
- Debugger: a tool that runs a program step by step while showing variable values.
- Breakpoint: a line where the debugger pauses the program.
Keep learning with Byte by Byte
Explore Book 7: Networks, Programming and Machine Learning. Find the ebook, purchase details and teaching slides on MemuniCity.
Comments
Post a Comment