How can I dynamically update a matrix containing f-string in Python?

I’m writing a console-based Tic-Tac-Toe game in Python, and I’ve got the definitions for the board and current placements of letters at the top:

board_dict = {'a1': ' ', 'b1': ' ', 'c1': ' ',
              'a2': ' ', 'b2': ' ', 'c2': ' ',
              'a3': ' ', 'b3': ' ', 'c3': ' '}

board = [[f'1:| {board_dict["a1"]} | ', f'{board_dict["b1"]} | ', f' {board_dict["c1"]}|'],
         [f'2:| {board_dict["a2"]} | ', f'{board_dict["b2"]} | ', f' {board_dict["c2"]}|'],
         [f'3:| {board_dict["a3"]} | ', f'{board_dict["b3"]} | ', f' {board_dict["c3"]}|']]

valid_choices = ['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']


def show_board():
    print('Showing board')
    print('  __A_|_B_|_C__')
    for row in board:
        print(row[0] + row[1] + row[2])
        print('  -------------')

When I redefine one of the items in board_dict, I expected the board matrix to respond accordingly, but it doesn’t.

I did manage to achieve the functionality by redefining the whole matrix:

def show_board():
    global board
    board = [[f'1:| {board_dict["a1"]} | ', f'{board_dict["b1"]} | ', f' {board_dict["c1"]}|'],
             [f'2:| {board_dict["a2"]} | ', f'{board_dict["b2"]} | ', f' {board_dict["c2"]}|'],
             [f'3:| {board_dict["a3"]} | ', f'{board_dict["b3"]} | ', f' {board_dict["c3"]}|']]
    print('Showing board')
    print('  __A_|_B_|_C__')
    for row in board:
        print(row[0] + row[1] + row[2])
        print('  -------------')

But my question is this:
Is there a way to make this happen dynamically without redefining the entire matrix each time? Or is this the only way?

>Solution :

Here’s a way to do it with string.format:

board_dict = {'a1': ' ', 'b1': ' ', 'c1': ' ',
              'a2': ' ', 'b2': ' ', 'c2': ' ',
              'a3': ' ', 'b3': ' ', 'c3': ' '}

board = ['1:| {a1} | {b1} | {c1} |',
         '2:| {a2} | {b2} | {c2} |',
         '3:| {a3} | {b3} | {c3} |']

valid_choices = ['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']

def show_board():
    print('Showing board')
    print('  __A_|_B_|_C__')
    for row in board:
        print( row.format(**board_dict) )
        print('  -------------')

show_board()

Output:

Showing board
  __A_|_B_|_C__
1:|   |   |   |
  -------------
2:|   |   |   |
  -------------
3:|   |   |   |
  -------------

Or, even simpler:

board_dict = {'a1': ' ', 'b1': ' ', 'c1': ' ',
              'a2': ' ', 'b2': ' ', 'c2': ' ',
              'a3': ' ', 'b3': ' ', 'c3': ' '}

board = '\n'.join([
         '  __A_|_B_|_C__',
         '1:| {a1} | {b1} | {c1} |',
         '  -------------',
         '2:| {a2} | {b2} | {c2} |',
         '  -------------',
         '3:| {a3} | {b3} | {c3} |',
         '  -------------'])

valid_choices = ['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']

def show_board():
    print('Showing board')
    print( board.format(**board_dict) )

show_board()

Leave a Reply