python-3.x - 使用 for 循环将字典转换为 csv 文件
问题描述
如何使用 for 循环将多个字典转换为 csv 文件(并将字典名称作为 csv 文件名)。另外,我将如何创建一个 for 循环来将 csv 文件读入根据 csv 文件名命名的单独字典。
我的问题是字典需要 12 个小时或更长时间才能在 jupyter notebook 中运行,我试图找到一种方法,让我的笔记本每次关闭时都不运行它们。
解决方案
最好提供您尝试过的代码和数据的小示例。
这假设字典是“扁平的”并且可以很容易地表示为 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
推荐阅读
- python - 使用递归和缓存的最长递增子序列
- python - Plotly 表达 choropleth 箱
- javascript - 嵌套在填充中的过滤器
- reactjs - 如何根据交替模式有条件地渲染?
- java - @ApplicationPath 中的多个资源 URL
- python - 如何将列表中的每个元素乘以其在列表 python 中的位置
- excel - Excel If 函数没有空行
- c - CaptureStackBackTrace 和 SymGetLineFromAddr64 无法获取线路信息返回错误代码 487
- caching - 如何停止在 wordpress litespeed 中缓存部分页面?
- swiftui - 将修改器应用于 VStack 内部视图