[英]Create a dictionary/list from a CSV file
I have a sheet like this and I want to group it into dictionary.我有一张这样的表格,我想将它分组到字典中。 I already imported and it is in this comma-separated format
我已经导入了,它是这种逗号分隔的格式
Accession,A,B,O,K,G,F
3364,+,-,+,-,+,-
3365,-+,-,+,-,+,-
3366,+,-,-,-,+,+
I want to put it like this:我想这样说:
{'3364': {'A': '+', 'B': '-', 'O': '+','K': '-', 'G': '+', 'F': '-'}}
How can I do that?我怎样才能做到这一点?
Jon is right, but here is a hint:乔恩是对的,但这里有一个提示:
d = {}
a = '3364,+,-,+,-,+,-'
n, *pm = a.split(',')
d[n] = {chr(i+65): v for i, v in enumerate(pm)}
print(d)
Here's a way with Python 3.4这是 Python 3.4 的一种方式
import csv
from pprint import pprint
a_dict = {}
with open('csv_data.csv', newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',', quotechar='|')
header = csvreader.__next__()
header_keys = header[1:]
for row in csvreader:
a_dict[row[0]] = {}
key_value = list(zip(header_keys, row[1:]))
a_dict[row[0]].update(key_value)
pprint(a_dict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.