72
Dictionaries and Structuring Data
113
what happens in a single turn (with white going first); for instance, the
notation 2. Nf3 Nc6 indicates that white moved a knight to f3 and black
moved a knight to c6 on the second turn of the game.
There’s a bit more to algebraic notation than this, but the point is that
you can use it to unambiguously describe a game of chess without needing
to be in front of a chessboard. Your opponent can even be on the other side
of the world! In fact, you don’t even need a physical chess set if you have a
good memory: You can just read the mailed chess moves and update boards
you have in your imagination.
Computers have good memories. A program on a modern computer
can easily store billions of strings like
'2. Nf3 Nc6'
. This is how computers can
play chess without having a physical chessboard. They model data to repre-
sent a chessboard, and you can write code to work with this model.
This is where lists and dictionaries can come in. You can use them to
model real-world things, like chessboards. For the first example, you’ll use
a game that’s a little simpler than chess: tic-tac-toe.
A Tic-Tac-Toe Board
A tic-tac-toe board looks like a large hash
symbol (#) with nine slots that can each
contain an X, an O, or a blank. To repre-
sent the board with a dictionary, you can
assign each slot a string-value key, as shown
in Figure 5-2.
You can use string values to represent
what’s in each slot on the board:
'X'
,
'O'
, or
' '
(a space character). Thus, you’ll need
to store nine strings. You can use a diction-
ary of values for this. The string value with
the key
'top-R'
can represent the top-right
corner, the string value with the key
'low-L'
can represent the bottom-left corner, the
string value with the key
'mid-M'
can repre-
sent the middle, and so on.
This dictionary is a data structure that represents a tic-tac-toe board.
Store this board-as-a-dictionary in a variable named
theBoard
. Open a
new file editor window, and enter the following source code, saving it as
ticTacToe.py:
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
'low-L': ' ', 'low-M': ' ', 'low-R': ' '}
The data structure stored in the
theBoard
variable represents the tic-tac-
toe board in Figure 5-3.
'low-L'
'low-M'
'low-R'
'mid-L'
'mid-M'
'mid-R'
'top-L'
'top-M'
'top-R'
Figure 5-2: The slots of a tic-tac-
toe board with their correspond-
ing keys