AvSmith
AvSmith

Reputation: 67

Saving a dictionary to a file

I am pretty new to Python, I am trying to take contents of my dictionary called python_diction(which is located in a larger file) and save that data to a new a new file called python_diction_saved.json. I feel like I am pretty close the error I am currently receiving is python_diction_saved.json is not defined.

Any help would be greatly appreciated.

import json
f = open("python_diction.txt","w")
python_diction = {}
python_diction["items"] = []
python_diction["items"].append({"hello":1,"hi":2})
python_diction["items"].append({"hello":42,"hi":65})
python_diction["numbers"] = [1,2,3,5,7,8]
f.write(json.dumps(python_diction_saved.json))
f.close()

Upvotes: 0

Views: 385

Answers (1)

Faibbus
Faibbus

Reputation: 1133

In order to write your python_diction to a file named python_diction_saved.json, you can use json.dump (to avoid having to write it yourself):

import json
python_diction = {}
python_diction["items"] = []
python_diction["items"].append({"hello":1,"hi":2})
python_diction["items"].append({"hello":42,"hi":65})
python_diction["numbers"] = [1,2,3,5,7,8]

with open("python_diction_saved.json") as output_file:
    json.dump(python_diction, output_file)

Upvotes: 1

Related Questions