如何使用for循环将多个字典转换为csv文件(并将字典名称用作csv文件名)。另外,我如何创建一个for循环来将csv文件读取到根据csv文件名命名的单独字典中。
我的问题是,在jupyter笔记本上运行字典需要12个小时或更长时间,我正在努力找到一种方法,不在每次笔记本关机时都运行它们。
发布于 2019-10-06 05:59:05
最好是提供你已经尝试过的代码和数据的小示例。
这假设字典是“平面的”,并且可以很容易地表示为csv文件。字典请注意,在编写任何python对象时,请考虑使用pickle
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_d2https://stackoverflow.com/questions/58252160
复制相似问题