简体   繁体   中英

How to print a tabular dictionary in Python

Suppose I have a dictionary of the form:

the_board = {(1,1) : ' ', (1,2) : ' ', (1,3) : ' ',
             (2,1) : ' ', (2,2) : ' ', (2,3) : ' ',
             (3,1) : ' ', (3,2) : ' ', (3,3) : ' ',}

I want to print each row line by line. Currently I do something like this:

def display(board):
    var = list(board.values())  # Iterator to print out the table
    i = 0
    j = 0
    maxi = len(var)
    while i < maxi:
        while j < (i + 3):
            print(var[j], end="")
            if j < i+2:
                print('|', end='')
            j += 1
        print()
        if i < (maxi-1):
            print("-+-+-")
        i += 3

I am aware that this is most likely not the most "pythonic way" to achieve what I want. How would I do so in a more pythonic manner? (I am aware that I can use the keys to achieve this since I gave them coordinate keys, but I may need to print a tabular dictionary without ordered/subscripted keys, so I would appreciate a more general solution).

Found out about Python's range function, so now my code looks like this:

def display(board):
    var = list(board.values())  # Iterator to print out the table
    maxi = len(var)
    for i in range(0, maxi, 3):
        for j in range(i, (i+3)):
            print(var[j], end="")
            if j < i+2:
                print('|', end='')
        print()
        if i < (maxi-1):
            print("-+-+-")

Still not sure it's the best way to write it.

def chunks(l,n):
""" Split list into chunks of size n """
    for i in range(0, len(l), n):
        yield l[i:i+n]

def display(board):
    for values in chunks(list(the_board.values()), 3):
        print('|'.join(values))    # use str.join to concat strings with separators
        print('-+-+-')

Hi If I understood you correctly this should be solution

board = {(1,1) : ' a ', (1,2) : ' b ', (1,3) : ' c  ',
             (2,1) : 'd ', (2,2) : 'e ', (2,3) : ' f ',
             (3,1) : 'g ', (3,2) : ' h', (3,3) : ' i',}

  print ( "Cordiantes --- Values")
  for key , value in board.items():
  print(key , "         " , value)

Output Will Be

在此处输入图片说明

You can set the number of columns:

the_board = {
    (1, 1): ' ', (1, 2): ' ', (1, 3): ' ',
    (2, 1): ' ', (2, 2): ' ', (2, 3): ' ',
    (3, 1): ' ', (3, 2): ' ', (3, 3): ' '
}


def display(board, ncols):
    items = list(board.values())
    separate_line = '\n' + '+'.join('-' * ncols) + '\n'
    item_lines = []
    i = 0
    while i + ncols <= len(items):
        item_line = '|'.join(items[i:i + ncols])
        item_lines.append(item_line)
        i += ncols
    output = separate_line.join(item_lines)
    print(output)


display(the_board, ncols=3)

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