0

I have a .txt file which is saved like this: {('A', 0): -1, ('A', 1): -1, ('A', 2): 0, ('B', 0): -1, ('B', 1): 0, ('B', 2): 0, ('C', 0): 0, ('C', 1): 0, ('C', 2): 0} which should become a dict if you code it like this dict = {('A', 0): -1, ('A', 1): -1, ('A', 2): 0, ('B', 0): -1, ('B', 1): 0, ('B', 2): 0, ('C', 0): 0, ('C', 1): 0, ('C', 2): 0} but if import the text from the file to a string so that the string is the raw text (like this txtfromfile = "{('A', 0): -1, ('A', 1): -1, ('A', 2): 0, ('B', 0): -1, ('B', 1): 0, ('B', 2): 0, ('C', 0): 0, ('C', 1): 0, ('C', 2): 0}" and I do this dict = txtfromfile it makes the dict a string. Is there a way to make it a dict instead of a string?

Koenvc
  • 3
  • 2

3 Answers3

3

You can use the literal_eval function from the ast built-in module:

import ast

with open("myfile.txt", "r") as fp:
    mydict = ast.literal_eval(fp.read())
Matt Pitkin
  • 3,989
  • 1
  • 18
  • 32
0

json.loads(text) will do the trick. https://docs.python.org/3/library/json.html

kpie
  • 9,588
  • 5
  • 28
  • 50
0

EDIT: Learned from the comment that eval should not be used for this. Explanation here. The proper solution is the answer suggesting ast.literal_eval().

You can should not use the following to evaluate the text:

txtfromfile = "{('A', 0): -1, ('A', 1): -1, ('A', 2): 0, ('B', 0): -1, ('B', 1): 0, ('B', 2): 0, ('C', 0): 0, ('C', 1): 0, ('C', 2): 0}"

my_dict = eval(txtfromfile)
print(my_dict)

Output:

{('A', 0): -1, ('A', 1): -1, ('A', 2): 0, ('B', 0): -1, ('B', 1): 0, ('B', 2): 0, ('C', 0): 0, ('C', 1): 0, ('C', 2): 0}
JANO
  • 2,995
  • 2
  • 14
  • 29