Python将CSV转换为列表字典

2024-05-15 05:24:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个CSV文件,如下所示:

compound, x1data,y1data,x2data,y2data
a,1,2,3,4
a,9,10,11,12
b,5,6,7,8
b,4,5,6,7

我想创建一个列表字典,其中复合词是键,对于每个复合词,我得到一个x1data、y1data、x2data和y2data的列表。你知道吗

我相信会是这样的:

my_dict = {
    'a': {'x1data':[1,9],'y1data':[2,10],'x2data':[3,11],'y2data':[4,12]},
    'b':{'x1data':[5,4],'y1data':[6,5],'x2data':[7,6],'y2data':[8,7]}
}

最后,我要为每种化合物绘制x1data vs y1data和x2data vs y2data。你知道吗

我试过这样做,它正确地生成了一个字典,其中键是复合词,但它没有给我一个值列表(只是csv中的最后一个值)。你知道吗

my_dict = {}
with open(filename, 'r') as infile:
    reader = csv.DictReader(infile)
    for row in reader:
        key = row.pop('compound')
        my_dict[key] = row

Tags: csv列表字典mydictinfilereaderrow
3条回答

这里有一种不用任何库的方法。你知道吗

f = open('f.csv', 'rb')
next(f)
mydict = {}
for row in f:

    compound,x1data,y1data,x2data,y2data = row.strip().split(',')
    x1data,y1data,x2data,y2data = int(x1data),int(y1data),int(x2data),int(y2data)
    if compound not in mydict:
        mydict[compound] = { 'x1data' : [], 'y1data' : [], 'x2data' : [], 'y2data' : [] }


    mydict[compound]['x1data'].append(x1data)
    mydict[compound]['y1data'].append(y1data)
    mydict[compound]['x2data'].append(x2data)
    mydict[compound]['y2data'].append(y2data)
}
f.close()

print mydict

给你:

{'a': {'x2data': [3, 11], 'y2data': [4, 12], 'y1data': [2, 10], 'x1data': [1, 9]}, 'b': {'x2data': [7, 6], 'y2data': [8, 7], 'y1data': [6, 5], 'x1data': [5, 4]}}

您可以使用itertools.groupby

import csv, itertools
[_, *hs], *data = csv.reader(open('filename.csv'))
r = [(a, [list(map(int, i[1:])) for i in b]) for a, b in itertools.groupby(data, key=lambda x:x[0])]
final_result = {a:dict(zip(hs, map(list, zip(*b)))) for a, b in r}

输出:

{'a': {'x1data': [1, 9], 'y1data': [2, 10], 'x2data': [3, 11], 'y2data': [4, 12]}, 'b': {'x1data': [5, 4], 'y1data': [6, 5], 'x2data': [7, 6], 'y2data': [8, 7]}}

您可以使用标准库中的collections.defaultdict。你知道吗

from collections import defaultdict as dd

import csv

my_dict = dd(lambda: dd(list))

with open("test.csv", 'r') as f:
    reader = csv.DictReader(f)

    for row in reader:
        for key in reader.fieldnames[1:]:
            my_dict[row.get("compound")][key].append(row[key])

严格来说,你在这里得到的不是dict。不过,你也可以用同样的方法。你知道吗

如果你想打印的话,需要更多的参与:

from pprint import pprint

# ...

pprint({k: dict(v) for k, v in dict(my_dict).items()})

这将提供:

{'a': {'x1data': ['1', '9'],
       'x2data': ['3', '11'],
       'y1data': ['2', '10'],
       'y2data': ['4', '12']},
 'b': {'x1data': ['5', '4'],
       'x2data': ['7', '6'],
       'y1data': ['6', '5'],
       'y2data': ['8', '7']}}

相关问题 更多 >

    热门问题