0

if I have a sample dictionary is it possible to output it to a new or existing .txt file?

d = {'Jim':'233-5467', 'Bob':'643-7894', 'Anne':'478-4392', 'Jill':'952-4532'}
Supernova
  • 63
  • 2
  • 10

3 Answers3

1

Use json module:

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

Or as @ZdaR suggested:

with open("file.json", "w") as out_file:
    json.dump(d, out_file)
Psidom
  • 209,562
  • 33
  • 339
  • 356
1

No modules needed.

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

Content of 'test.txt' :

Jill:952-4532 Bob:643-7894 Jim:233-5467 Anne:478-4392

Anil_M
  • 10,893
  • 6
  • 47
  • 74
0

You have to convert it to json, json can represent dict in txt format.

import json
json.dump({'Jim':'233-5467', 'Bob':'643-7894', 'Anne':'478-4392', 'Jill':'952-4532'}, open('yourfile.json', 'w'))
Nilesh
  • 20,521
  • 16
  • 92
  • 148