Python Dictionaries for Games
Python dictionaries explained with games: rules tables for Rock Paper Scissors, rooms in a text adventure, counting letters, and looping with items().
A dictionary stores key: value pairs, so you can look something up by name instead of by position. Games use them for rules, rooms, item stats and score tables.
Looping through a dictionary
Counting with get()
d.get(key, 0) returns 0 when the key is missing instead of crashing, which makes counting easy.
Dictionaries inside dictionaries
A text adventure's world is a dictionary of rooms, where each room is another dictionary with its description, exits and items. See Lighthouse Island for the full example.
💡 Looking up a missing key with d[key] raises KeyError. Check with if key in d or use d.get(key).
Games that use Dictionaries
Practise this with 5 of the 20 games:
- #02☆☆☆
Rock Paper Scissors in Python
Learn The random module, Dictionaries and if, elif and else.
- #08☆☆☆
Text Adventure Game in Python
Learn Dictionaries, Strings and while loops.
- #15☆☆☆
Word Guessing Game in Python
Learn Strings, Lists and Dictionaries.
- #18☆☆☆
Python Quiz Game
Learn Dictionaries, Lists and for loops.
- #19☆☆☆
Math Quiz Game in Python
Learn The random module, Dictionaries and for loops.
Frequently asked questions
When should I use a dictionary instead of a list?
Use a list when order and position matter (a board, a queue). Use a dictionary when you look things up by a name or key (rules, rooms, scores).
Are Python dictionaries ordered?
Yes. Since Python 3.7 dictionaries keep the order in which keys were added.