1

I have a .txt file formatted like a dictionary is, for example:

{'planet': 'earth', "country": "uk"}

Just that, that's all. I would want to add more to this later. At the moment, I can save more keys to it and have it saved but...

How can I import this .txt file and use it as a dictionary?

jt2456
  • 13
  • 4
  • 2
    Use one of the many canonical serialization formats, i.e. JSON, YAML, pickle etc. In this case, you should probably just use JSON. Don't roll your own serialization, and don't dump the string representation of yourobjects to a text file and call it serialization. – juanpa.arrivillaga Jul 17 '18 at 22:59
  • 1
    write to the file as JSON and read it as JSON using the `json` module – JacobIRR Jul 17 '18 at 22:59

1 Answers1

1

You can use ast.literal_eval

import ast
with open('myfile.txt') as f:
    mydict = ast.literal_eval(f.read())

Some extra reading on using eval vs ast.literal_eval.

aydow
  • 3,673
  • 2
  • 23
  • 40