首页 > 解决方案 > 将多个字典转换为 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 值。我希望它成为一个列表。

标签: pythondictionary

解决方案


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
...

推荐阅读