Reputation: 151
I have a csv that looks like this:
Name;Category;Address
McFood;Fast Food;Street 1
BurgerEmperor;Fast Food;Way 1
BlueFrenchHorn;French;Street 12
PetesPizza;Italian;whatever
SubZero;Fast Food;Highway 6
and I want to make a dictionary with the category as keys and a list of dictionaries with the remaining data as values. So it shall look like this:
{'Fast Food' : [{'Name': 'McFood', 'Address': 'Street 1'},
{'Name': 'BurgerEmperor', 'Address': 'Way 1'}],
...],
'French' : [{'Name': 'BlueFrenchHorn', 'Address': 'Street12'}],
...}
(indentation here for better readability).
I tried it like the following snippet but I do not get anywhere from there:
import csv
mydict={}
with open ('food.csv', 'r') as csvfile:
#sniff to find the format
fileDialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
#read the CSV file into a dictionary
dictReader = csv.DictReader(csvfile, dialect=fileDialect)
for row in dictReader:
mycategory= row["Category"]
del row("Category")
mydict[mycategory]=row
Upvotes: 1
Views: 592
Reputation: 369494
Using collections.defaultdict
:
import csv
from collections import defaultdict
mydict = defaultdict(list) # <---
with open ('food.csv', 'r') as csvfile:
fileDialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
dictReader = csv.DictReader(csvfile, dialect=fileDialect)
for row in dictReader:
mycategory= row.pop("Category")
mydict[mycategory].append(row) # Will put a list for not-existing key
mydict = dict(mydict) # Convert back to a normal dictionary (optional)
Upvotes: 4