如何将两个具有不同键,值对的字典组合到一个字典中,并将结果写入标头及其值的txt文件中?

时间:2018-10-15 20:39:01

标签: python python-3.x dictionary

我有以下两个字典:

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实现呢?

1 个答案:

答案 0 :(得分:1)

根据卡尔的评论进行构建:

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()