2017-03-02 58 views

回答

1

无需模块。

myfile = open('test.txt','w') 
d = {'Jim':'233-5467', 'Bob':'643-7894', 'Anne':'478-4392', 'Jill':'952-4532'} 
myfile.writelines('{}:{} '.format(k,v) for k, v in d.items()) 
myfile.close() 

'的test.txt' 的内容:

吉尔:952-4532鲍勃:643-7894吉姆:233-5467安妮:478-4392

+0

谢谢@Anil_M – Supernova

1

使用json模块:

import json 
json.dump(d, open("file.json", "w")) 

或者为@ZdaR建议:

with open("file.json", "w") as out_file: 
    json.dump(d, out_file) 
0

你必须把它转换成JSON,json可以txt格式代表dict

import json 
json.dump({'Jim':'233-5467', 'Bob':'643-7894', 'Anne':'478-4392', 'Jill':'952-4532'}, open('yourfile.json', 'w'))