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?
Asked
Active
Viewed 37 times
0

Koenvc
- 3
- 2
-
import json then use json.loads(string) – Jeremy Savage Jan 24 '22 at 16:11
-
1@JeremySavage That would only work if the dictionary keys were strings. Here, though, the keys are tuples. – jjramsey Jan 24 '22 at 16:14
-
How was the text file created in the first place? Was it intended to be a JSON, but didn't because of keys being tuples? – buran Jan 24 '22 at 16:18
-
@jjramsey Ahh didn't know that, thanks! – Jeremy Savage Jan 24 '22 at 16:18
3 Answers
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
-
1That won't work with dictionaries that have tuples as keys, which is what the opening post has. – jjramsey Jan 24 '22 at 16:12
-
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