python将带有行和列标题的csv文件读入带有两个键的字典中

新手上路,请多包涵

我有以下格式的 csv 文件,

 ,col1,col2,col3
row1,23,42,77
row2,25,39,87
row3,48,67,53
row4,14,48,66

我需要将其读入两个键的字典中,以便

dict1['row1']['col2'] = 42
dict1['row4']['col3'] = 66

如果我尝试使用带有默认选项的 csv.DictReader

 with open(filePath, "rb" ) as theFile:
    reader = csv.DictReader(theFile, delimiter=',')
    for line in reader:
    print line

我得到以下输出

{'': 'row1', 'col2': '42', 'col3': '77', 'col1': '23'}
{'': 'row2', 'col2': '39', 'col3': '87', 'col1': '25'}
{'': 'row3', 'col2': '67', 'col3': '53', 'col1': '48'}
{'': 'row4', 'col2': '48', 'col3': '66', 'col1': '14'}

我不确定如何处理此输出以创建我感兴趣的字典类型。

为了完整起见,如果您可以解决如何将字典写回具有上述格式的 csv 文件,这也会有所帮助

原文由 rambalachandran 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 311
2 个回答

使用 CSV 模块:

 import csv
dict1 = {}

with open("test.csv", "rb") as infile:
    reader = csv.reader(infile)
    headers = next(reader)[1:]
    for row in reader:
        dict1[row[0]] = {key: int(value) for key, value in zip(headers, row[1:])}

原文由 Tim Pietzcker 发布,翻译遵循 CC BY-SA 3.0 许可协议

你可以为此使用 pandas ,即使它有点矫枉过正。优点是几乎无需编写代码即可获得预期结果。

 # Reading the file
df = pd.read_csv('tmp.csv', index_col=0)

# Creating the dict
d = df.transpose().to_dict(orient='series')

print(d['row1']['col2'])
42

原文由 Romain 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题