Storing coordinate based grids, planes, maps or levels inside a Python dictionary has a few benefits (and a few negative tradeoffs) compared to lists of lists.
Benefit 1: neighbour check
For example, if we have a grid of
we could store it as
but if we ever need to check any neighbouring cells, we need to manually make sure we don’t cross any index boundaries. For example, in (0, 0)
, we need to remember to check that a neighbour at (-1, 0)
cannot be accessed.
If we instead store this as a dictionary with (x, y)
keys:
we can always access any index, regardless of it doesn’t exist:
and if there’s a default value that’s not None
, we can define that as well:
Benefit 2: sparse grids
Sometimes in Advent of Code puzzles, we don’t need to store the state of every coordinate. For example in the following:
where .
is considered “empty”, we could only store the coordinates where there is an X
and treat every missing coordinate as .
when accessing them with .get()
as above.
Downside: iterating over
One downside of a dictionary approach is if we need to do a lot of iterating over the individual cells, especially if we have a sparse grid.
We need to keep track of the smallest and largest x
and y
and do nested for
loops:
It’s also very easy to make one-off errors with this. Ask me how I know.
If we have a full grid with coordinates filled in right order we can usually loop over the keys: