python - 将多个字典转换为 csv 表的最快方法
问题描述
我有一个 for 循环,它在循环的每次迭代中创建 2 种 dict
dict1= {'a':'hello', 'b':"13/12/2019", 'c':23.45}
dict2: {'tax_type':"duties taxes", 'Charges':25.00,'Total':9.23}
因此,在 for 循环的某些迭代中,我将创建第一个,而在其他一些迭代中,我将创建第二个。这重复多次
最后,我想要一个 csv 文件,它应该将这两个字典键作为列标题,将值作为行,用于 for 循环的相同迭代。
所以像:
a | b | c | tax_type | Charges | Total
------------------------------------------------------
hello | 13/12/2019| 23.45 |duties taxes| 25.00 | 9.23
当 for 循环的下一次传递发生时,上面的另外 2 个新 dict 将在那里,我希望将它们作为新记录添加到上面的 csv 中,位于同一列标题下。
我想如果我可以继续将在 for 循环的每次传递中创建的这 2 个 dict 添加到第三个 dict,然后最终将最终 dict 转换为 csv,这是一种方法。但困难在于如何将上述dicts的值在每个pass中添加为list的元素。
使用dict.update(dict1)
ordict.update(dict2)
会覆盖之前的 pass dict 值。我希望它成为一个列表。
解决方案
import pandas as pd
lst = []
dict1 = {}
dict2 = {}
# for loop
for i in range(100):
# simulating the staggered creation of dict1 and dict2 below
if condition1:
dict1 = {'a':'hello', 'b':"13/12/2019", 'c':23.45}
if condition2:
dict2 = {'tax_type':"duties taxes", 'Charges':25.00,'Total':9.23}
if dict1 and dict2:
lst.append({**dict1, **dict2})
dict1 = {}
dict2 = {}
df = pd.DataFrame(lst)
print(df.to_string())
输出:
a b c tax_type Charges Total
0 hello 13/12/2019 23.45 duties taxes 25.0 9.23
1 hello 13/12/2019 23.45 duties taxes 25.0 9.23
...
推荐阅读
- python - OSError:SavedModel 文件不存在于:C:\Users\Munib\New 文件夹/{saved_model.pbtxt|saved_model.pb}
- json - 颤振下拉按钮评估来自json的值
- python - 用 Python 解析大型复杂的专利分类 XML 文件
- python - 根据 Django 中的用户权限有条件地重定向到不同的仪表板
- powershell - 如何使用 Powershell 重置宽限期
- javascript - 从 Firebase 获取数据时,来自 Redux Toolkit 的 createAsyncThunk 会产生未定义的有效负载
- excel - 如何使用户窗体中的两个文本框互斥
- android - 可扩展回收站视图不显示我的项目
- visual-studio-code - 如何在 VS Code 中创建“终端配置宏”?轻松打开和拆分多个终端
- csv - 如何为 Jmeter 中的每次出现传递不同的 CSV 值