i have created a python Ordered Dictionary by importing collections and stored it in a file named 'filename.txt'. the file content looks like
OrderedDict([(7, 0), (6, 1), (5, 2), (4, 3)])
i need to make use of this OrderedDict from another program. i do it as
myfile = open('filename.txt','r')
mydict = myfile.read()
i need to get 'mydict' as of Type
<class 'collections.OrderedDict'>
but here, it comes out to be of type 'str'.
is there any way in python to convert a string type to OrderedDict type? using python 2.7
Here's how I did it on Python 2.7
Again, you should probably write your text file differently.
You could store and load it with pickle
The best solution here is to store your data in a different way. Encode it into JSON, for example.
You could also use the
pickle
module as explained in other answers, but this has potential security issues (as explained witheval()
below) - so only use this solution if you know that the data is always going to be trusted.If you can't change the format of the data, then there are other solutions.
The really bad solution is to use
eval()
to do this. This is a really really bad idea as it's insecure, as any code put in the file will be run, along with other reasonsThe better solution is to manually parse the file. The upside is that there is a way you can cheat at this and do it a little more easily. Python has
ast.literal_eval()
which allows you to parse literals easily. While this isn't a literal as it uses OrderedDict, we can extract the list literal and parse that.E.g: (untested)
This is not a good solution but it works. :)