Loop through a list and compare each string of a list to a row in a csv file [Python]

Viewed 32

I have a list of teams. I would like to go through this list of teams and for each team that exists in a row of a csv I would like to append it to a variable that I can call later.

Here is my code and I cant seem to get it to work.

    object = input('Object ID')
        
    my_list = ['team1', 'team2', 'team3', 'team4']
    for i in my_list:
        team_list = [i]
        
    with open(latest_csv) as report:
        reader = list(csv.reader(report, delimiter= ','))
              
        def obj():
            values = []
            for row in reader:
                if row[3] == team_list and row[14] == object: 
                    values.append([row[3], row[4],row[5], row[14]])
            return values```

example of csv file
|Country| City | State | Team Name| ..... | Object |
|-------|------|-------|----------|-------|--------|
|USA    |Denver| CO    | team1    |       | 1      |
|USA    |NY    | NY    | team2    |       | 1      |
|USA    |ATL   | GA    | team3    |       | 2      |
|USA    |Bost  | MA    | team4    |       | 2      |
1 Answers

So, this is my solution: I used a similar dataframe because your previous versions didn't match with the question.

my_list = ['team1', 'team2', 'team3', 'team4']
# df
Country City    Team Name   Teams
0   USA Denver  team1   Broncos
1   USA NY      team2   Giants
2   USA ATL     team3   Falcons
3   USA BOST    team4   Patriots

The solution:

fields = {key: [] for key in my_list} # The dictionary to keep the values

fields # {'team1': [], 'team2': [], 'team3': [], 'team4': []}

for i in df.values:
    for j in my_list:
        if i[2] == j:
            fields[j].append(i)

The Output:

{'team1': [array(['USA', 'Denver', 'team1', 'Broncos'], dtype=object)],
 'team2': [array(['USA', 'NY', 'team2', 'Giants'], dtype=object)],
 'team3': [array(['USA', 'ATL', 'team3', 'Falcons'], dtype=object)],
 'team4': [array(['USA', 'BOST', 'team4', 'Patriots'], dtype=object)]}
Related