I am relatively new to programming and have been trying to learn python. I have a problem that I spent a few hours in and can't seem to wrap my head around how to solve it.
I have a CSV file that contains some data I want to loop through the data and create a dictionary where the key is the person and the value is a dictionary where the key is an item and the value is how many of that item they have. I also want to exclude some data I don't care about. In this example let say I don't care how many pineapples they have.
Example CSV Data:
Name Fruit Bob, Apples Bob, Pineapple Bob, Apples Bob, Oranges Bob, Oranges Bob, Oranges Bob, Kiwi Kate, Oranges Kate, Pineapple Kate, Oranges Kate, Apples Mary, Kiwi Mary, Pineapple
Expected outcome = {Bob: {Apples:2, Oranges:3, Kiwi:1} Kate:{Oranges:2, Apple:1} Mary:{Kiwi:1}}
This is what I came up with so far but I when it runs when it gets to the second person the count is off because it doesn't reset the count after each user.
import csv
from collections import Counter
fruitToAnalyze = ['Apple','Oranges','Kiwi']
final = {}
fruitlist = []
with open("data.csv") as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
next(csvfile)
for row in readCSV:
person = row[0]
fruit = row[1]
if fruit in fruitToAnalyze:
fruitlist.append(fruit)
countedfruitlist = Counter(fruitlist)
final[person] = countedfruitlist
I can't seem to figure out a way to reset the Counter for each person and the count for the everyone after the first person is wrong because it's adding it is counting for the whole list not each person.
Actual outcome:
{Bob: {Apples:2, Oranges:3, Kiwi:1} Kate:{Oranges:5, Apple:3} Mary:{Kiwi:2, Oranges:5, Apple:3}}
I may not be even going about this the right way. Open to how to solve this or a better way to do this