【问题标题】:Combine 5 dictionaries together as save as txt file python将5个字典组合在一起保存为txt文件python
【发布时间】:2021-06-21 04:34:33
【问题描述】:

我有以下 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 文件。输出应如下所示:

{{'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')

这不会正确合并和保存输出。我怎样才能做到这一点?

【问题讨论】:

  • 检查json.dump(d, file)
  • 也许你写的是 ('b') 而不是 ('d') 因为你说它没有正确保存。

标签: python pandas dictionary merge save


【解决方案1】:

你不需要 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}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多