在Python中从csv在字典中创建词典列表

发布于 2021-01-29 15:02:15

我有一个看起来像这样的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': '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
关注者
0
被浏览
87
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    使用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)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看