The best solution here is to store your data in a different way. Encode it in JSON , for example.
You can also use the pickle module , as explained in other answers, but this has potential security issues (as explained using eval() below) - so use this solution only if you know that the data will always be trusted.
If you cannot change the data format, then there are other solutions.
A very bad solution is to use eval() for this. This is a really bad idea indeed , because it is unsafe, since any code placed in a file will run along with other reasons
The best solution is to manually parse the file. The good news is that you can fool it and make it a little easier. Python has ast.literal_eval() , which makes it easy to parse literals. Although this is not a literal, since it uses an OrderedDict, we can extract a literal list and parse it.
For example: (unverified)
import re import ast import collections with open(filename.txt) as file: line = next(file) values = re.search(r"OrderedDict\((.*)\)", line).group(1) mydict = collections.OrderedDict(ast.literal_eval(values))
source share