简体   繁体   English

将5个字典组合在一起保存为txt文件python

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

I have the following 5 dictionaries:我有以下 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}

I would like to merge these five dictionaries and save as a txt file.我想合并这五个字典并保存为 txt 文件。 The output should look like the following: output 应如下所示:

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

or或者

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

What I tried so far?到目前为止我尝试了什么?

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

This doesn't merge and save the output properly.这不会正确合并和保存 output。 How can I achieve that?我怎样才能做到这一点?

You don't need pandas for file handling (for this problem at least).您不需要 pandas 来处理文件(至少对于这个问题)。

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

merges your dictionaries properly.正确合并您的字典。 To save this data as txt file, you only need python file handling:要将这些数据保存为 txt 文件,您只需要 python 文件处理:

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

Content of file.txt: 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