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?
-
import json then use json.loads(string)Jeremy Savage– Jeremy Savage2022-01-24 16:11:02 +00:00Commented Jan 24, 2022 at 16:11
-
1@JeremySavage That would only work if the dictionary keys were strings. Here, though, the keys are tuples.jjramsey– jjramsey2022-01-24 16:14:58 +00:00Commented Jan 24, 2022 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– buran2022-01-24 16:18:18 +00:00Commented Jan 24, 2022 at 16:18
-
@jjramsey Ahh didn't know that, thanks!Jeremy Savage– Jeremy Savage2022-01-24 16:18:54 +00:00Commented Jan 24, 2022 at 16:18
Add a comment
|
3 Answers
json.loads(text) will do the trick.
https://docs.python.org/3/library/json.html
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}
1 Comment
buran
please, don't suggest eval or exec for a task like this.