簡體   English   中英

將5個字典組合在一起保存為txt文件python

[英]Combine 5 dictionaries together as save as txt file python

我有以下 5 個字典:

d1 = {'a': 1, 'b': 2}
d2 = {'b': 10, 'c': 11}
d3 = {'e': 13, 'f': 15}
d4 = {'g': 101, 'h': 111}
d5 = {'i': 10, 'j': 11}

我想合並這五個字典並保存為 txt 文件。 output 應如下所示:

{{'a': 1, 'b': 2}, {'b': 10, 'c': 11}, {'e': 13, 'f': 15}, {'g': 101, 'h': 111}, {'i': 10, 'j': 11}}

或者

{'a': 1, 'b': 2, 'b': 10, 'c': 11, 'e': 13, 'f': 15, 'g': 101, 'h': 111, 'i': 10, 'j': 11}

到目前為止我嘗試了什么?

d = {**d1, **d2, **d3, **d4, **d5}
df = pd.DataFrame.from_dict(d, orient='index')
df.to_csv('output.txt')

這不會正確合並和保存 output。 我怎樣才能做到這一點?

您不需要 pandas 來處理文件(至少對於這個問題)。

d = {**d1, **d2, **d3, **d4, **d5}

正確合並您的字典。 要將這些數據保存為 txt 文件,您只需要 python 文件處理:

with open('file.txt', 'w') as file:
    # first convert dictionary to string
    file.write(str(d))

file.txt 的內容:

{'a': 1, 'b': 10, 'c': 11, 'e': 13, 'f': 15, 'g': 101, 'h': 111, 'i': 10, 'j': 11}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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