You can use the eval
built-in. For example, this would work if each dictionary entry is on a different line:
dicts_from_file = []
with open('myfile.txt','r') as inf:
for line in inf:
dicts_from_file.append(eval(line))
# dicts_from_file now contains the dictionaries created from the text file
Alternatively, if the file is just one big dictionary (even on multiple lines), you can do this:
with open('myfile.txt','r') as inf:
dict_from_file = eval(inf.read())
This is probably the most simple way to do it, but it's not the safest. As others mentioned in their answers, eval
has some inherent security risks. The alternative, as mentioned by JBernardo, is to use ast.literal_eval
which is much safer than eval since it will only evaluate strings which contain literals. You can simply replace all the calls to eval
in the above examples with ast.literal_eval
after importing the ast
module.
If you're using Python 2.4 you are not going to have the ast
module, and you're not going to have with
statements. The code will look more like this:
inf = open('myfile.txt','r')
dict_from_file = eval(inf.read())
inf.close()
Don't forget to call inf.close()
. The beauty of with
statements is they do it for you, even if the code block in the with
statement raises an exception.
ast.literal_eval
ast
module was introduced in 2.5, but didn't have the helper functions (such asliteral_eval
). Those came in 2.6.