4

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
                     }
            }
4
  • 1
    Why don't you use pickle instead? Commented Mar 22, 2018 at 23:25
  • Seems easier to just load the file as json this_dict = json.load(open("dict_file.json")) instead of generating source code. Commented Mar 22, 2018 at 23:32
  • 2nd the usage of pickle stackoverflow.com/questions/4530611/… Commented Mar 22, 2018 at 23:38
  • Dictionaries don't have names. Commented Mar 23, 2018 at 0:50

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.