Home > Enterprise >  How to show dictionary data in table format in terminal
How to show dictionary data in table format in terminal

Time:11-01

I am trying to solve the simple usecase where I need to show data in terminal in tabular style not needed fancy table but somehow that emits like table.

here is my code.

score = {'rounds_0': {'jack': 9, 'joe': 8}, 'rounds_1': {'jack': 11, 'joe': 13}}

players_name = ["jack","joe"]
for each_rounds in range(0,2):
    print(f"""              ********Round {each_rounds   1}****""", end='')
print()

for player, each_rounds in zip(players_name, range(0,2) ):
   print(player,score.get(f'rounds_{each_rounds}').get(player))

currently my output is as follows

              ********Round 1****              ********Round 2****
jack 9
joe 13

I am trying to include round_0 dict value unders Round 1 column and similary Round 2 for round_1 like this and if possible sum of each row

              ********Round 1****              ********Round 2****          *****Total*****
jack                 9                                  11                       20
joe                  8                                  13                       21                    

I really tried some for loop concepts but can't figure out how I do it as I am really beginner in python any help will be really great.

CodePudding user response:

You're iterating players and rounds together, but what you need to do is iterate players and then rounds for each player. It's probably easier to generate a list of scores for each player and then print that:

score = {'rounds_0': {'jack': 9, 'joe': 8}, 'rounds_1': {'jack': 11, 'joe': 13}}
players = list(score['rounds_0'].keys())
rounds = range(len(score.keys()))
print(f"          {''.join(f' **** Round {rd} **** ' for rd in rounds)} **** Total ****")
for player in players:
    scores = [score[f'rounds_{rd}'].get(player, 0) for rd in rounds]
    print(f"{player:10s}{''.join(f'{s:^20d}' for s in scores)}{sum(scores):^15d}")

Output:

           **** Round 0 ****  **** Round 1 ****  **** Total ****
jack               9                   11               20
joe                8                   13               21
  • Related