Read Python csv file to group players into teams and save them in dictionaries

Asked 2 weeks ago, Updated 2 weeks ago, 2 views

I am currently teaching myself dictionary and list. There's something I can't understand, so I'm uploading it.

First of all, the csv file is written with open on Python and opened.

import csv

with open("practice.csv") as f:
    file = csv.reader(f)
    file = list(file)

The csv file was simply written like this.

What should I do if I want to save the players in Team A and the players in Team B in a dictionary?

For example, if you run print(new_dict), (new_dict) on the terminal is a dictionary that I want to store all the information. ) {'A': 'The names of the players in Team A', 'B': 'The names of the players in Team B...} I want it to come out like this.

Thank you.

This is the code I wrote down by myself.

import csv

with open("practice.csv") as f:
    file = csv.reader(f)
    file = list(file)

new_dict = {}
new_dict[file[1][0]] = file[1][1]

i = 2

while (i<len(file)):
    if file[i][0].lower() == "a":
        new_dict[file[1][0]] += (f' {file[i][1]}')
        i += 1
        new_dict[file[i][0]] = file[i][1]
        i += 1

print (new_dict)

When I run this, it says {'A': 'aaaaa', 'B': 'bb', 'D': 'dd'} but I don't know how to modify it.

python dictionary list csv

2022-09-20 14:31

2 Answers

To give you the overall direction, it is as follows...

First, refer to: This is what I got from this site.

Searcher -> I found it by searching for "Python CSV" on Google. (Let's make Google search a daily life!)

import csv

f = open('example.csv','r')
rdr = csv.reader(f)

for line in rdr:


->(Example of execution results)
['A', 'a']
['B', 'b']
['A', 'aa']
['D', 'd']

In this code, line is loading data for each row of Excel. Put csv.reader(f) in a variable called rdr and turn it into a for statement to output csv. In other words, in the for statement above, data is saved in the form of a list by simply appending a line to another variable instead of print(line).

After that, the first value of the list (Team A, Team B) is taken out as another iteration, checked whether it is A or B as an if statement, and then put it in a global variable called team_A, team_B.

I think you can make the chords, so try typing in detail...

2022-09-20 14:31

It's actually much more convenient to do things like this with Pandas. The code is also readable.

import pandas as pd

df = pd.read_csv("practice.csv")

# # print(df)

grouped = df.groupby("team name")["player name"].agg(lambda x: ' '.join(x))

# # ->
# # | team name   | player name   |
# |:------------|:--------------|
# # | A           | a aa aaa      |
# # | B           | b bb          |
# # | D           | d dd          |

new_dict = {}
for k, g in df.groupby("team name"):
    # # print(k)
    # # print(' '.join(g["player name"]))
    new_dict[k] = ' '.join(g["player name"])

# # -> {'A': 'a aa aaa', 'B': 'b bb', 'D': 'd dd'}

2022-09-20 14:31

If you have any answers or tips

© 2022 pinfo. All rights reserved.