簡體   English   中英

將多個字典轉換為 csv 表的最快方法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM