我在字典中有数据。如何将所有密钥写入文件(.txt)格式?
答案 0 :(得分:0)
ab={'engy':'011199887765',
'wafa2':'87878857578',
'heba':'6677553636'}
with open('D:\glo.txt','w') as f:
for name, mobile in ab.items():
print ('Contact %s at %s' % (name, mobile))
f.write(name)
这只是一个例子,你需要做一些修改。
答案 1 :(得分:0)
您可以使用dict.keys()
从字典中提取密钥:
d = {'foo' : 1, 'bar' : 2}
fname = 'keys.txt'
with open(fname, 'w') as f:
f.write('\n'.join(d.keys()))
f.write('\n') # newline at the end of file
print "Keys saved to {}.".format(fname)