本文介绍了在Python中从csv创建词典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv如下:

 名称;类别;地址
McFood;快餐; Street 1
BurgerEmperor; Fast Food; Way 1
BlueFrenchHorn; French; Street 12
PetesPizza; Italian;无论
SubZero; Fast Food; Highway 6

,我想制作一个类别为键的字典和一个字典列表,其余数据为值。所以它应该是这样的:

  {'Fast Food':[{'Name':'McFood','Address' :'b'b {'Name':'BurgerEmperor','Address':'Way 1'}],
...],
'French':[{ 'Name':'BlueFrenchHorn','Address':'Street12'}],
...}

(缩进这里是为了更好的可读性)。



我尝试像下面的代码片段,但我没有从那里得到任何地方:

  import csv 
mydict = {}

with open('food.csv','r')as csvfile:
#sniff找到格式
fileDialect = csv.Sniffer()。sniff(csvfile.read(1024))
csvfile.seek(0)
#read CSV文件转换成字典
dictReader = csv.DictReader(csvfile,dialect = fileDialect)
for dict in dictReader:
mycategory = row [Category]
del row(范畴上y)
mydict [mycategory] ​​=行


解决方案

p>使用:

  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)
在dictReader中的行:
mycategory = row.pop (Category)
mydict [mycategory] ​​.append(row)#将列出不存在的键

mydict = dict(mydict)#转换为普通字典可选)


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
解决方案

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)

这篇关于在Python中从csv创建词典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 05:29