gpt4 book ai didi

python - 如何快速将csv表导出到python字典?

转载 作者:行者123 更新时间:2023-12-01 00:32:47 24 4
gpt4 key购买 nike

我有一个 csv 表,其中包含化合物及其属性和描述,我希望将其导出到 Python 字典中:

csv table

上表应转换为以下字典:

compound_data = {COMPOUND 1:{'Property 1':'Description 1', 'Property 2':'Description 2', 'Property 3':'Description 3', 'Property n':'Description n'}, COMPOUND 2:{'Property 1':'Description 1', 'Property 2':'Description 2', 'Property x':'Description x'}, COMPOUND n:{'Property y':'Description y', 'Property z':'Description z'}}

表中有数百种化合物,每种化合物都有不同数量的属性。化合物可能具有相同的特性(例如沸点),也可能具有独特的特性(例如电导率)。我编写了一些访问复合信息的代码,如下所示:

compound_data['COMPOUND 1']['Property 1'] = 'Description 1'

将表读入Python字典的最简单、最Python化的方法是什么?

最佳答案

这应该可以。

import csv    

with open('csv_file.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
compound_dictionary = dict()
last_compound_key = str()
for row in csv_reader:
if row[0] != '':
last_compound_key = row[0]
compound_dictionary[last_compound_key] = dict()

compound_dictionary[last_compound_key][row[1]] = row[2]

print(compound_dictionary)

关于python - 如何快速将csv表导出到python字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58046249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com