0

What I'm trying to do, is backup a dictionary into a text file. This is what my code looks like so far:

with open("dict.txt","r") as dict_file:
    text = dict_file.read()
    my_dict = text

Of course, this makes a variable called 'my_dict' but saves what is in the text file as a string.

Inside the text file, I have this:

{"test":["test0","test1"],"dict":["dict0","dict1","dict2"]}

If you are wondering why I'm doing this, it is for a challenge I am doing with my friends where we have to make a user-database thing with importing and exporting users to a text file.

jpp
  • 159,742
  • 34
  • 281
  • 339
  • Possible duplicate of [Writing a dict to txt file and reading it back?](https://stackoverflow.com/questions/11026959/writing-a-dict-to-txt-file-and-reading-it-back) – jpp Mar 29 '18 at 10:42

2 Answers2

2

You can use the ast module to convert the sting object to a dictionary.

Ex:

import ast
d = '{"test":["test0","test1"],"dict":["dict0","dict1","dict2"]}'
print(ast.literal_eval(d))

Output:

{"test":["test0","test1"],"dict":["dict0","dict1","dict2"]}

Or you can use the JSON module.

Ex:

import json
with open("dict.txt","r") as dict_file:
    text = json.load(dict_file)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0
import json
with open("dict.txt", 'r') as dict_file:
    my_dict = json.load(dict_file)
stamaimer
  • 6,227
  • 5
  • 34
  • 55
  • 2
    Thanks for posting an answer. It's always good practice to add some additional comments to your answer and why it solves the problem, rather than just posting a code snippet. – sebs Mar 29 '18 at 13:55