2

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

Dash
  • 125
  • 4

2 Answers2

0

If you can assume the CSV file is sorted by the names (like in the example you gave) you could reset fruitlist every time you encounter a new name:

prevPerson = ''
for row in readCSV:
    person = row[0]
    fruit = row[1]
    if (prevPerson != person):
        fruitlist = []
    prevPerson = person
    if fruit in fruitToAnalyze:
        fruitlist.append(fruit)
        countedfruitlist = Counter(fruitlist)
        final[person] = countedfruitlist

Otherwise, you keep a fruitlist array for every person, and only after you finish, you turn it to Counter.

for row in readCSV:
    person = row[0]
    fruit = row[1]
    if fruit in fruitToAnalyze:
        if (person not in final):
            final[person] = []
        final[person].append(fruit)
... # finish code
for person in final.keys():
    final[person] = Counter(final[person])
Gershon Papi
  • 5,008
  • 3
  • 24
  • 50
  • Your first example was what i was thinking I have to do but wasn't sure how to do it. But like like the second one better. While this data is nice and neat and in order I like the idea of being able to handle it if it's out of order. – Dash Jul 18 '17 at 01:01
0

I'm not sure if you really need a counter. You can simply initialize a default dictionary

Note: This method doesn't assume people are not inter-mixed in your file

import csv

fruitToAnalyze = {'Apples','Oranges','Kiwi'}
final = {}

with open("data.csv") as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    next(csvfile)
    for row in readCSV:
        person = row[0]
        # Initializes only one person dict
        if person not in final:
            final[person] = {f: 0 for f in fruitToAnalyze}  
        fruit_counter = final[person]
        fruit = row[1].strip()
        if fruit in fruitToAnalyze:
            fruit_counter[fruit] += 1

Output {'Bob': {'Oranges': 3, 'Kiwi': 1, 'Apples': 2}, 'Kate': {'Oranges': 2, 'Kiwi': 0, 'Apples': 1}, 'Mary': {'Oranges': 0, 'Kiwi': 1, 'Apples': 0}}

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • That worked nicely but can you explain the {f: 0 for f in fruitToAnalyze} line. not sure what that is doing – Dash Jul 18 '17 at 00:56
  • Dict comprehension. https://stackoverflow.com/questions/1747817/create-a-dictionary-with-list-comprehension-in-python – OneCricketeer Jul 18 '17 at 00:56