简体   繁体   中英

Printing python lists inside dictionary vertically

output_dictionary = {
    "inputs": [3,5,10],
    "squared": [9,25,100],
    "cubed": [27,125,1000],
}

print('Number\tSquare\tCube')

for key, value in output_dictionary.items():
    # for num in value:
    #     print(num, end="\t")
    # print()
    for i in range(3):
        print(value[i], end="\t")
    print()

I want to print the output in this way

Number  Square  Cube
3       9       27
5       25      125
10      100     1000

I tried several methods but can't figure it out.

Here is the solution:

output_dictionary = {
    "inputs": [3,5,10],
    "squared": [9,25,100],
    "cubed": [27,125,1000],
}

headers = ["Number", "Square", "Cube"]
values = output_dictionary.values()

row_format ="{:>10}" * (len(headers) + 1)
print(row_format.format("", *headers))

for value, row in zip(headers, values):
    print(row_format.format("", *row))

Will produce:

  Number   Square     Cube
    3         5        10
    9        25        100
    27       125       1000

Here is another solution, in line with Federer's remark.

o = {
    "inputs": [3,5,10],
    "squared": [9,25,100],
    "cubed": [27,125,1000],
}

print('Number\tSquare\tCube')

for i in range(3):
    print(f'{o["inputs"][i]}\t {o["squared"][i]}\t {o["cubed"][i]}')
print()
print('Number   Square  Cube')

for count in range(3):
    for i in output_dictionary:
        print(output_dictionary[i][count], end="\t")
    print()

I finally figured it out. The printing loop comes like this. Thanks, everyone for the help!

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