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?

4
  • import json then use json.loads(string) Commented Jan 24, 2022 at 16:11
  • 1
    @JeremySavage That would only work if the dictionary keys were strings. Here, though, the keys are tuples. Commented 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? Commented Jan 24, 2022 at 16:18
  • @jjramsey Ahh didn't know that, thanks! Commented Jan 24, 2022 at 16:18

3 Answers 3

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())
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

That won't work with dictionaries that have tuples as keys, which is what the opening post has.
Oh shoot, good point.
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}

1 Comment

please, don't suggest eval or exec for a task like this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.