Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 14th, 2012  |  syntax: None  |  size: 0.65 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. string to OrderedDict conversion in python
  2. OrderedDict([(7, 0), (6, 1), (5, 2), (4, 3)])
  3.        
  4. myfile = open('filename.txt','r')
  5. mydict = myfile.read()
  6.        
  7. <class 'collections.OrderedDict'>
  8.        
  9. import cPickle as pickle
  10.  
  11. # store:
  12. with open("filename.pickle", "w") as fp:
  13.     pickle.dump(ordered_dict, fp)
  14.  
  15. # read:
  16. with open("filename.pickle") as fp:
  17.     ordered_dict = pickle.load(fp)
  18.  
  19. type(ordered_dict) # <class 'collections.OrderedDict'>
  20.        
  21. import re
  22. import ast
  23. import collections
  24.  
  25. with open(filename.txt) as file:
  26.     line = next(file)
  27.     values = re.search(r"OrderedDict((.*))", line).group(1)
  28.     mydict = collections.OrderedDict(ast.literal_eval(values))