Saving A Dictionary to a File


#1

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
f.write(json.dumps(python_diction_saved.json))
AttributeError: 'dict' object has no attribute 'json'

Any help would be greatly appreciated!

import json

f = open("test.py","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]
python_diction_saved = python_diction
f.write(json.dumps(python_diction_saved.json))
f.close()

#2

f is the file you are writing to, what is between the brackets of dumps() is what you write to the file


#3

Good point! Maybe I am executing this the wrong way. I have a dictionary in a file called test.py, this file contains other information besides the dictionary. What I am trying to do is take only the dictionary called python_diction and save that data to a new file called python_diction_saved.json. Any suggestions? Thanks!


#4

yes, you are executing it the wrong way. You are currently writing to f, which is test.py

i know what you wanted to achieve. lets walk through my answer:

lets see what is in f:

f = open("test.py","w")

test.py, you didn't intent to write to test.py

I was actually hoping you could have made this leap on your own :wink:


#5

Yes, that makes sense! Below is my new code, but I feel like I am overcomplicating this. Since the dictionary"python_diction" I want to write to another file is currently in the file test.py do I need to open and read through test.py first? With the below code I am currently getting ValueError: No JSON object could be decoded.

import json 
f = open("test.py","r")
python_obj = json.loads(f.read())
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]
python_diction_saved.json = python_diction
fw = open ("python_diction_saved.json","w")
fw.write(json.dumps(fw))
fw.close()

#6

you are not over complicating, you read from one file, and write to another, if we where to do this in office word we also need to open two files, so same here in python, why is that over complicating?

you should currently write fw (which is your file) to your file.... Uhm... no?