【问题标题】:How to combine two dicts with different key, value pairs into a single dictionary and write the result into a txt file with header and their values? [closed]如何将具有不同键、值对的两个字典组合成一个字典,并将结果写入带有标题及其值的 txt 文件? [关闭]
【发布时间】:2018-10-15 20:39:00
【问题描述】:

我有两个字典如下:

dict1 = {'name':'john', 'age':43}
dict2 = {'sex':'male', 'place':'southafrica'}

注意:dict2 的键和值可以随时更改

我们如何像这样组合两个字典:

res = {'name':'john', 'sex':'male', 'place':'southafrica'}

我想将它写入一个带有分隔符“|”的 txt 文件如下图”

name|sex|place
john|male|southafrica

我们如何使用 python 实现这一点?

【问题讨论】:

  • “年龄”43 岁会怎样?
  • 为什么不打印年龄?并且可能与How to merge two dictionaries in a single expression? 重复
  • 您是否关心原始字典之一是否被修改?您可以拨打dict1.update(dict2)将dict2添加到dict1。
  • 我们不需要 dict1['age'] 这个@wim
  • @WalterWhite:然后明确说明需要什么和不需要什么。组合规则是什么?

标签: python python-3.x dictionary


【解决方案1】:

根据 Karl 的评论构建:

dict1 = {'name':'john', 'age':43}
dict2 = {'sex':'male', 'place':'southafrica'}

# combine the dicts
dict1.update(dict2)

# Get the keys
keys = dict1.keys()

# Get the values corresponding to each key in proper order
values = [dict1[key] for key in keys]

# Write to a file
fout = open('fileout.txt','w')
print('|'.join(map(str, keys)), file=fout)
print('|'.join(map(str, values)), file=fout)
fout.close()

【讨论】:

  • 谢谢@killian95。根据 cmets 进行更改。现在可以了。
  • 你能展示如何在不打印的情况下使用分隔符写入文件吗? @killian95
  • 好的,现在更新我的答案。
  • 它没有写入文件。该文件为空。它会抛出一个错误,说不支持的操作数 >> ? @kiilian95
  • 啊,你一定用的是python 3。我的语法是python 2的。更新中。
猜你喜欢
  • 2019-07-02
  • 2019-09-18
  • 1970-01-01
  • 2017-07-23
  • 1970-01-01
  • 1970-01-01
  • 2015-11-15
  • 2017-07-14
  • 1970-01-01
相关资源
最近更新 更多