Home > Software engineering >  How do I print all values of a dictionary in order?
How do I print all values of a dictionary in order?

Time:09-22

I am a rookie. Collectively, I have about two weeks of experience with any sort of computer code.

I created a dictionary with some baseball player names, their batting order, and the position they play. I'm trying to get it to print out in columns with "order", "name", and "position" as headings, with the order numbers, positions, and names under those. Think spreadsheet kind of layout (stackoverflow won't let me format the way I want to in here).

order name position 1 A Baddoo LF 2 J Schoop 1B 3 R Grossman DH

I'm new here, so apparently you have to click the link to see what I wrote. Dodgy, I know...

As you can see, I have tried 257 times to get this thing to work. I've consulted the google, a python book, and other sources to no avail.

CodePudding user response:

Here is the working code

for order in lineup["order"]:
    order -= 1
    position = lineup["position"][order]
    name = lineup["name"][order ]
    print(order   1, name, position)

Your Dictionary consists of 3 lists - if you want entry 0 you will have to access entry 0 in each list separately.

This would be an easier way to use a dictionary

players = {1: ["LF", "A Baddoo"],
           2: ["1B", "J Schoop"]}
for player in players:
    print(players[player])

Hope this helps

CodePudding user response:

Pandas is good for creating tables as you describe what you are trying to do. You can convert a dictionary into a a dataframe/table. The only catch here is the number of rows need to be the same length, which in this case it is not. The columns order, position, name all have 9 items in the list, while pitcher only has 1. So what we can do is pull out the pitcher key using pop. This will leave you with a dictionary with just those 3 column names mentioned above, and then a list with your 1 item for pitcher.

import pandas as pd

lineup = {'order': [1,2,3,4,5,6,7,8,9],
          'position': ['LF', '1B', 'RF','DH','3B','SS','2B','C','CF'],
          'name': ['A Baddoo','J Schoop','R Grossman','M Cabrera','J Candelario', 'H Castro','W Castro','D Garneau','D Hill'],
          'pitcher':['Matt Manning']}


pitching = lineup.pop('pitcher')
starting_lineup = pd.DataFrame(lineup)

print("Today's Detroit Tigers starting lineup is: \n", starting_lineup.to_string(index=False), "\nPitcher: ", pitching[0])

Output:

Today's Detriot Tigers starting lineup is: 
  order position         name
     1       LF     A Baddoo
     2       1B     J Schoop
     3       RF   R Grossman
     4       DH    M Cabrera
     5       3B J Candelario
     6       SS     H Castro
     7       2B     W Castro
     8        C    D Garneau
     9       CF       D Hill 
Pitcher:  Matt Manning
  • Related