从Python中的csv创建字典中的字典列表
我有一个csv,看起来像这样:从Python中的csv创建字典中的字典列表,python,list,csv,dictionary,Python,List,Csv,Dictionary,我有一个csv,看起来像这样: 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 {'Fast Food' : [{'Name': 'McFood', 'Address': 'Street 1'},
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
{'Fast Food' : [{'Name': 'McFood', 'Address': 'Street 1'},
{'Name': 'BurgerEmperor', 'Address': 'Way 1'}],
...],
'French' : [{'Name': 'BlueFrenchHorn', 'Address': 'Street12'}],
...}
我想制作一个以类别为键的字典,以及一个以剩余数据为值的字典列表。所以它应该是这样的:
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
{'Fast Food' : [{'Name': 'McFood', 'Address': 'Street 1'},
{'Name': 'BurgerEmperor', 'Address': 'Way 1'}],
...],
'French' : [{'Name': 'BlueFrenchHorn', 'Address': 'Street12'}],
...}
(此处缩进以提高可读性)
我像下面的代码片段一样尝试了它,但没有得到任何结果:
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
使用:
导入csv
从集合导入defaultdict
mydict=defaultdict(list)#使用:
导入csv
从集合导入defaultdict
mydict=defaultdict(列表)#