I have got a dictionary this_dict
produced in a python script that I would like to write to a separate python module dict_file.py
. This would allow me to load the dictionary in another script by importing dict_file
.
I thought a possible way of doing this was using JSON, so I used the following code:
import json
this_dict = {"Key1": "Value1",
"Key2": "Value2",
"Key3": {"Subkey1": "Subvalue1",
"Subkey2": "Subvalue2"
}
}
with open("dict_file.py", "w") as dict_file:
json.dump(this_dict, dict_file, indent=4)
When I opened the resulting file in my editor, I got a nicely printed dictionary. However, the name of the dictionary in the script (this_dict
) was not included in the generated dict_file.py
(so only the braces and the body of the dictionary were written). How can I include the name of the dictionary too?
I want it to generate dict_file.py
as follows:
this_dict = {"Key1": Value1,
"Key2": Value2,
"Key3": {"Subkey1": Subvalue1,
"Subkey2": Subvalue2
}
}