Home > OS >  dictionary code in file to dictionary in python
dictionary code in file to dictionary in python

Time:01-25

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?

CodePudding user response:

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())

CodePudding user response:

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

CodePudding user response:

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}
  •  Tags:  
  • Related