[Tutor] HELP!!

Joel Goldstick joel.goldstick at gmail.com
Tue Jan 12 17:56:44 EST 2016


On Tue, Jan 12, 2016 at 3:36 PM, Chelsea G <cegarcia0323 at gmail.com> wrote:

> So I am importing a csv file to textfile and the first column is product
> names and the second is a description of each. I am trying to find the sum
> of all descriptions using sum(c.values)). Here is my code so far:
>
> import csv
> import json
> import sys
> #from sys import argv
> from collections import defaultdict
> from collections import Counter
> #script, filename = argv
> data = defaultdict(list)
> counted_data = defaultdict(list)
> grouped_data = defaultdict(list)
>
> class dictionary:
> with open ('weekly_20160102.csv', 'rb') as f:
> reader = csv.reader(f)
> next(reader, None)
> for row in reader:
> data[row[2]].append(row[3]) #this appends the description(value) to the
> product name(key)
> #new_item = {}
> for key in data.keys():
> #print key
> c = Counter(data[key])
> for value in c:
> #print c[value]
> if c[value] >= 5:
> print key, ':', value, ':', c[value]
> elif c[value] <= 1:
> print 'other', ':', sum(c.values())
>
>
> Please help!!
>

First of all, turn off your rich text mail editor -- we can only help if we
see the indentation.  Send Text only to this list.
You define a class, but never instantiate it.  what is Counter()?  Where is
it defined?

This is awfully complicated.  If your csv file looks like this:

name1, 5
name3, 54
name2, 3
name1, 4

you can read the file line by line, split on , and add the second value to
a dict with the first value as a key.  You will need to check for the
exception of their being no key with that value (the first time it appears).

But first, resend in plain text

> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
http://joelgoldstick.com/stats/birthdays


More information about the Tutor mailing list