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
}
}
1) use file.write:
file.write('this_dict = ')
json.dump(this_dict, dict_file)
2) use write + json.dumps, which returns a string with json:
file.write('this_dict = ' + json.dumps(this_dict)
3) just print it, or use repr
file.write('this_dict = ')
file.write(repr(this_dict))
# or:
# print(this_dict, file=file)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With