Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string to OrderedDict conversion in python

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

like image 620
srek Avatar asked Dec 12 '22 02:12

srek


1 Answers

You could store and load it with pickle

import cPickle as pickle

# store:
with open("filename.pickle", "w") as fp:
    pickle.dump(ordered_dict, fp)

# read:
with open("filename.pickle") as fp:
    ordered_dict = pickle.load(fp)

type(ordered_dict) # <class 'collections.OrderedDict'>
like image 131
wong2 Avatar answered Dec 28 '22 11:12

wong2