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.

example 1 · press Run, then edit and run again

Looping through a dictionary

example 2 · press Run, then edit and run again

Counting with get()

d.get(key, 0) returns 0 when the key is missing instead of crashing, which makes counting easy.

example 3 · press Run, then edit and run again

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:

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.

More Python concepts