0

I know this has been asked before but I can't figure it out for my situation.

I want to read in player stats from a csv file into a nested dictionary. The intended result is something like this:

dictionary = {
  "player1": {
    "goals" : 5,
    "assists" : 7,
    "games played" : 50
  },
  "player2": {
    "goals" : 4,
    "assists" : 8,
    "games played" : 49
  },
  "player3": {
    "goals" : 6,
    "assists" : 10,
    "games played" : 53
  },
}

The csv file looks like this:

Player  Goals  Assists  Games Played
player1 5      7        50
player2 4      8        49
player3 6      10       53

In the end I want to be able to access a players stats by calling, for example:

x = dictionary.get("player1")
print(x)

Very new to python so any help on how to achieve this would be much appreciated!

A1i50n
  • 35
  • 3

1 Answers1

3

Instead of a dictionary, consider using the pandas module. It allows easy access to columns and rows in a way that other Python data structures make difficult.

You can bring your CSV into what is called a dataframe in Pandas, then access rows where certain values match what you're looking for, such as player1.

dataframe = pandas.read_csv("players.csv")
player_column = dataframe["Player"]
player1_row = dataframe.loc[player_column == "player1"]

.loc locates the row where the value in the player column (Player) is equal to player1.

More on Pandas here.

aero-man
  • 115
  • 10