Reputation: 43
I currently have a csv file that holds a user's name and their score on a quiz (out of 10). The csv file looks like this:
Ben,8
Tim,9
Tim,10
Ben,10
Ben,9
Tim,7
I would like to group the data in a dictionary so a user's name is entered only once and so that it can hold all the user's scores on the quiz (as far as I am aware it is not possible to do in a csv file). The dictionary should look like this:
scores = {'Ben': [8, 10, 9], 'Tim': [9, 10, 7], etc...}
How can I group the data from the csv file into a dictionary in this way?
I have tried searching for a key e.g. 'Ben' in the dictionary however it only returns the most recent score by 'Ben' in the CSV file.
Many thanks.
Upvotes: 0
Views: 275
Reputation: 883
Have a look at the following example using defaultdict:
from collections import defaultdict
d = defaultdict(list)
with open('data.csv') as data:
for line in data:
name, score = line.strip("\n").split(',')
d[name].append(int(score))
print d
Output:
defaultdict(<type 'list'>, {'Tim': [9, 10, 7], 'Ben': [8, 10, 9]})
Upvotes: 3
Reputation:
Here is an example:
sc_txt='''\
Ben,8
Tim,9
Tim,10
Ben,10
Ben,9
Tim,7'''
import csv
scores={}
for line in csv.reader(sc_txt.splitlines()):
scores.setdefault(line[0], []).append(line[1])
print scores
# {'Tim': ['9', '10', '7'], 'Ben': ['8', '10', '9']}
Just replace sc_txt.splitlines()
with an open file object and you are golden.
Upvotes: 0