[英]Fastest way to convert multiple dictionary to a csv table
我有一个 for 循环,它在每次循环迭代中创建 2 种字典
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 个新的字典,我希望将它们添加到上面的 csv 作为相同列标题下的新记录。
我想如果我可以继续将在 for 循环的每次传递中创建的这 2 个字典添加到第三个字典,然后最终将最终字典转换为 csv,这是一种方法。 但难点在于如何在每次传递中将上述字典的值添加为列表的元素。
使用dict.update(dict1)
或dict.update(dict2)
会覆盖之前传递的字典值。 我希望它成为一个列表。
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())
Output:
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
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.