23. Dictionaries — Homework solutions

The .py solution files are in exercises/23/homework/solutions/.

Problem 1 — Player record

Problem. Build a player dictionary; print each field with .items().

How to think about it. A literal with the four keys, a for k, v in player.items(): loop, one print per pair.

Worked solution.

player = {
    "name": "Keiko",
    "class": "Mage",
    "level": 7,
    "alive": True,
}

for key, value in player.items():
    print(key, value)

Python 3.7+ preserves insertion order, so the fields print in the order you wrote them.

Common mistakes.

  • Writing player.name instead of player["name"]. Python dictionaries do not support dot notation — that syntax is for object attributes.
  • Using player[name] (no quotes). name without quotes is a variable; Python looks up the variable name, not the string "name".

Problem 2 — Inventory weights

Problem. Sum the values in a dictionary.

How to think about it. Use .items() or .values(). Keep a running total like in Chapter 22. Alternatively, sum(d.values()) does it in one call.

Worked solution.

inventory = {
    "sword": 3.5,
    "shield": 5.0,
    "potion": 0.2,
    "map": 0.1,
    "coins": 0.05,
}

total = 0
for _, weight in inventory.items():
    total = total + weight

print(f"Total weight: {total:.2f}")

Or shorter:

print(f"Total weight: {sum(inventory.values()):.2f}")

The _ ignores the key; the sum only needs the values.

Common mistakes.

  • Trying for i, weight in enumerate(inventory):. enumerate on a dictionary gives you the keys, not the values. Use .values() or .items().

Problem 3 — Safe lookup

Problem. lookup(d, key) returns the value or "(not found)".

How to think about it. Check key in d first. Return the value if found; otherwise return the placeholder string. Alternatively, use .get(key) and check for None.

Worked solution.

def lookup(d, key):
    if key in d:
        return d[key]
    return "(not found)"

player = {"name": "Keiko", "level": 7}

print(lookup(player, "name"))     # Keiko
print(lookup(player, "email"))    # (not found)

key = "level"
print(lookup(player, key))        # 7

Common mistakes.

  • Using if d[key]: instead of if key in d:. When the key is missing, d[key] raises a KeyError before the if can evaluate. Always check membership with in first.
  • Using if d.get(key): and forgetting that False and 0 are falsy. A dictionary storing "flag": False would be wrongly reported as not found. The key in d check avoids that.

Challenge — Word frequency

Problem. Count occurrences of each word in a list.

How to think about it. Walk the list once. For each word, look it up in counts; if it is not there yet, treat the count as 0, then add 1 and store it back.

The Python idiom is counts.get(word, 0) — it returns 0 when the word is not yet in the dictionary.

Worked solution.

words = ["apple", "banana", "apple", "cherry", "apple", "banana"]

counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1

for word, count in counts.items():
    print(word, count)

Output (in insertion order):

apple 3
banana 2
cherry 1

Common mistakes.

  • Writing counts[word] = counts[word] + 1 without .get(word, 0). The first time a word is seen, counts[word] raises a KeyError.
  • Using collections.Counter. That is the production tool and works perfectly, but building the loop by hand first shows you the mechanics.

Done?

Next, List methods gives you ready-made tools for sorting, reversing, and transforming lists, and the last chapter of Part 5 splits code across files using modules. After that, the Part 5 mini-project — a Text Adventure — combines dictionaries, functions, and modules into a tiny game world.