Skip to main content

Featured

Space Explorers Book 7: Answers and Explanations

Memunic Space Explorers › Book 7: Memoon and the Search for Another Home › Answers and Explanations Answers and Explanations Habitable means life could live there; inhabited means life does live there. A world can be habitable and empty, as an unoccupied flat has a roof and water but nobody in it. The Moon has almost no air, so water would boil or freeze, and its gravity is only about one-sixth of Earth’s, too weak to keep air. Accept also: no greenhouse blanket, so it swings between very hot and very cold. Venus. It matches Earth in size and roughly in mass, but its thick carbon dioxide air traps heat, making it hot and crushing. “Twin” is only true for size and weight. A dip of 1 per cent means (planet width divided by star width) squared is 0.01, so the ratio is 0.1: the planet is about a tenth as wide as the star. Repeats at the same gap show the planet is going round the star in 12 days, and rule out a one-time event such as a passing object. A planet shines only by reflected l...

Byte by Byte Book 7: Chapter 7 – Dictionaries and Program Design

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.

CodeWhat 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"] = 4Changes an existing value
account["flagged"] = TrueAdds 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
VariableYou have one valuescore = 95
StringYou have textname = "Vega"
ListYou have many values in an orderA list of posts in time order
TupleA fixed group of values that should not change("06:42", "echo_4471")
DictionaryYou look things up by name or labelOne profile; word counts
List of dictionariesMany records with the same fieldsAll 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:

  1. One function, one job. If you need the word and to describe it, split it.
  2. Meaningful names for variables and functions: follower_count , not fc .
  3. 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.
  4. Comments explain why, not what. # accounts made after the attack began are suspicious helps; # add 1 to x does not.
  5. A main() function that reads like a summary of the program, calling the other functions in order.
  6. Test each function as you write it, not all at the end.

Three kinds of error.

KindWhen it happensExampleHow you notice

Syntax error Before the program runs: Missing colon after if ; Python refuses to run

the code breaks Python's grammar rulesunclosed bracketand 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 answeradding instead of multiplyingdata 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() called print_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.

  1. Reproduce it: find an input that always causes the problem.
  2. Read the error message and traceback carefully.
  3. Trace the values: add temporary print() lines showing variables at key points, or do a dry run with a trace table (Book 6).
  4. Narrow it down: test each function on its own until you find the one giving the wrong result.
  5. Fix one thing at a time, then test again, including the tests that passed before.
  6. 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.

  1. In the Python Shell window (not the editor), click Debug → Debugger. A Debug Control window opens and the shell shows [DEBUG ON] .
  2. Go back to your program and press F5 to run it. It pauses on the first line.
  1. 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.
  2. Tick Locals and Globals to watch the variables change.
  3. To pause at a particular line, right-click it in the editor and choose Set Breakpoint (it turns yellow), then click Go.
  4. 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.

Illustration from Byte by Byte Book 7: Chapter 7 – Dictionaries and Program Design

🛠️ 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

  1. What is a dictionary? How is looking something up in a dictionary different from looking it up in a list?
  2. Write a dictionary describing yourself with at least four keys.
  3. 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.
  4. What is the difference between pet["owner"] and pet.get("owner") when the key does not exist?
  5. What is printed? print("cat" in {"type": "cat"}) . Explain.
  6. Write a loop that prints every key and value in pet in the form name = Noodles .
  7. Complete this counting code so it counts each letter in a word: counts = {} / for ch in "banana": / counts[ch] =
  8. When would you use a list of dictionaries instead of one dictionary?
  9. Name the three kinds of error and give one example of each.
  10. In which direction should you read a traceback, and what does its last line tell you?
  11. 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.
  12. Challenge: Write a program for a school library. Store each book as a dictionary with title, author, year and a "borrowed" value of True or False , 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.

Watch this chapter on YouTube

Comments

Popular posts from this blog

CA-7 Job Status and Failure Reason Codes

Here are the various status codes that You may see for jobs in the Queue or Logs in CA-7. R-C0002 R-C0003 R-C0099 R-C0255 R-JCLER A-U0002 A-U0004 A-U0015 A-U0043 A-U4095 A-SOC7 A-U4000 Reason Code/Job Status Code explanation: The indication of the job's current disposition. Values and their meanings are: A-Snnnn-- The job has failed with a system abend. A-Unnnn --The job has failed with a user abend. C-Cnnnn --The job has completed successfully and is going through completion processing. E-ARFATT-- An error occurred during the attempt to attach ARF definitions. This can result if the ARFSET specified is not defined. A diagnostic message may have been written to the CA-7 log, the OS console, or to the trailer queue for the job (in which case it can be displayed using LQ,JOB=x,LIST=ALL). E-ARFERR ---The job encountered an error in the ARF processing. Do a LARFQ command for the job to get more specific information. E-SEGERR --The job has been requeued...

Whistling Winds and Waterfalls: 4 Days of Magic in Shillong

Nestled in the clouds, where the scent of pine trees mingles with the rhythm of waterfalls and the tunes of local guitar-strumming youth—Shillong is more than a place. It’s a vibe. If you’ve got 3 nights and 4 days, you’ve got just enough time to fall in love. Here’s how to make the most of it—food, fun, fog and fantastic views included. Day 1: Shillong, We’re Coming for You! You land in Guwahati, barely out of the airport when the hills start calling. You hop into your cab, Spotify on, windows down, and the three-hour ride to Shillong begins. Just when you think it can’t get better, you stop at Umiam Lake —a lake so calm, it looks like someone ironed the water. By evening, you’re sipping hot chai in Laitumkhrah, maybe nibbling on spicy momos or pork jadoh from a roadside stall. You’re checked into your charming hotel ( Tripura Castle if you fancy old-world royalty, Ri Kynjai if you’re into lakeside poetry). The breeze whispers secrets of waterfalls and pine forests. Sleep well, drea...

Installing and Configuring Hadoop on Ubuntu as a Pseudo Distributed Single Node Cluster

Briefly what is psuedo-distributed single node Hadoop cluster: It is a Hadoop distributed cluster having Single Node. All the five daemons (NN,DN,JT,TT,SNN) are running as individual JVM (java process) instances. We will get all distributed features of Hadoop. This mode is used to develop, test, and staging (before production) Map Reduce programs quickly. It writes all the system, daemon and user logs to different files on the cluster To install Hadoop in this mode, we have to modify the hadoop-env.sh, core-site.xml, hdfs-site.xml, mapred-site.xml. hadoop-env.sh contains all the Environment variables which are required for running Hadoop. All the default values are fine, Only we have to modify the JAVA_HOME=“The location of Java Home Directory” Core-site.xml contains all the cluster specific information like io, temp directory, sorting, file system uri etc. Hdfs-site.xml contains all the parameters which are specific to HDFS like name node directory, data node directory...