我有以下两个字典:
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实现呢?
答案 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()