首页 > 解决方案 > 使用 for 循环将字典转换为 csv 文件

问题描述

如何使用 for 循环将多个字典转换为 csv 文件(并将字典名称作为 csv 文件名)。另外,我将如何创建一个 for 循环来将 csv 文件读入根据 csv 文件名命名的单独字典。

我的问题是字典需要 12 个小时或更长时间才能在 jupyter notebook 中运行,我试图找到一种方法,让我的笔记本每次关闭时都不运行它们。

标签: python-3.xpandascsv

解决方案


最好提供您尝试过的代码和数据的小示例。

这假设字典是“扁平的”并且可以很容易地表示为 csv 文件。字典的注意事项考虑使用 pickle 代替编写任何 python 对象

import pandas as pd

# dictionaries o f data
d1 = {'item11':1, 'item12': 2}
d2 = {'item21':3, 'item22': 4}

# dictionary of the data dictionaries with names
dicts = {'d1' : d1, 'd2' : d2}

# use pandas to make a dataframe and the write data frame to csv
for a_dict in dicts:
    pd.DataFrame.from_dict(dicts[a_dict], orient="index", columns=['value']).to_csv("~/Downloads/"+a_dict+".csv", index_label="key")

# Reading into new names
new_d1 = pd.read_csv("~/Downloads/" + "d1" + ".csv", index_col=0).to_dict(orient='dict')['value']
new_d2 = pd.read_csv("~/Downloads/" + "d2" + ".csv", index_col=0).to_dict(orient='dict')['value']

assert d1 == new_d1
assert d2 == new_d2

推荐阅读