Skip to content
Codewilds

Lesson 23 of 34 · Dictionaries & Sets

Boss: Index a Spellbook with Python Dicts and Sets

Boss battlehard100 XP1 min read

Quillgrave the Spectral Archivist blocks the way. Every test you pass deals damage — pass them all to defeat it and claim a loot chest.

Deep in the Hollow's great library, Quillgrave the Spectral Archivist has torn every spell out of its book and shuffled them into one chaotic list. Index the spellbook with dictionaries and sets before the ink fades for good.

Battle plan

A spellbook is a list of (name, school, mana_cost) tuples:

spellbook = [
    ("Fireball", "fire", 30),
    ("Ember", "fire", 10),
    ("Frost Nova", "ice", 25),
    ("Ice Lance", "ice", 15),
    ("Heal", "light", 20),
]

You'll need the grouping and counting patterns (setdefault() and get()), set comprehensions, and set operations. Unpacking three values at once works just like two: for name, school, cost in spellbook:.

Assignment

Write four functions. None of them may modify the spellbook they receive.

1. spells_by_school(spells) returns a dictionary mapping each school to a list of its spell names, in the order the spells appear.

2. mana_by_school(spells) returns a dictionary mapping each school to the total mana cost of all its spells.

3. castable(spells, mana) returns a set with the names of all spells whose cost is less than or equal to mana.

4. shared_schools(book_a, book_b) returns an alphabetically sorted list of the schools that appear in both spellbooks.

spells_by_school(spellbook)
# {"fire": ["Fireball", "Ember"], "ice": ["Frost Nova", "Ice Lance"], "light": ["Heal"]}
mana_by_school(spellbook)
# {"fire": 40, "ice": 40, "light": 20}
castable(spellbook, 20)
# {"Ember", "Ice Lance", "Heal"}
shared_schools(spellbook, [("Spark", "fire", 5), ("Shadow Bolt", "shadow", 35)])
# ["fire"]

Premium lesson

Unlock the full Learn Python course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Keep learning

Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.

Lesson last updated on .

Write code ↓
Python+100 XP

Lesson 23 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn Python course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.