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
}
}
答案 0 :(得分:0)
If you don't want to use pickle
as @roganjosh proposed in the comments, a hacky workaround would be the following:
this_dict = {"Key1": "Value1",
"Key2": "Value2",
"Key3": {"Subkey1": "Subvalue1",
"Subkey2": "Subvalue2"
}
}
# print the dictionary instead
print 'this_dict = '.format(this_dict)
And execute the script as:
python myscript.py > dict_file.py
Note: Of course this assumes that you will not have any other print statements on myscript.py
.
答案 1 :(得分:0)
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)