简体   繁体   中英

How do you format a dictionary into a 5x5 grid?

I'm trying to print my dictionary into a 5x5 grid but dont know how to do that.

game_dict = {(0,0): 0, (0,1): 0, (0,2): 0, (0,3): 0, (0,4): 0, 
             (1,0): 0, (1,1): 0, (1,2): 0, (1,3): 0, (1,4): 0,
             (2,0): 0, (2,1): 0, (2,2): 0, (2,3): 0, (2,4): 0,
             (3,0): 0, (3,1): 0, (3,2): 0, (3,3): 0, (3,4): 0,
             (4,0): 0, (4,1): 0, (4,2): 0, (4,3): 0, (4,4): 0}

print(*game_dict.values())

This prints out 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

I would like it to print

0 0 0 0 0
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0

current_position = (0, 0)

game_dict[str(current_position)] ="X"

X 0 0 0 0
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0

You can do what you want quite easily, by iterating through your coordinates:

width = 5
height = 5
for y in range(height):
    row = [game_dict[(x, y)] for x in range(width)]
    print(*row)

However, if your coordinates are always integers, you can make this even simpler by just using a list of lists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM