I have a text file containing python dictionaries. The thing is when I extract these dictionaries using ast.literal_eval
the order changes and I know it is supposed to change as dictionaries are unordered data structures.
>>> import ast
>>> fp = open('file','r')
>>> dic = fp.readline()
>>> dic
"{'7': {'16': 'a', '15': {'10': {'9': {'8': 'a'}}, '12': {'11': 'a'}, '14': {'13': 'a'}}, '6': {'3': {'1': 'a', '2': 'a'}, '5': 'a', '4': 'a'}}}\n"
>>> dic1 = ast.literal_eval(dic.strip())
>>> dic1
{'7': {'6': {'3': {'1': 'a', '2': 'a'}, '5': 'a', '4': 'a'}, '15': {'10': {'9': {'8': 'a'}}, '12': {'11': 'a'}, '14': {'13': 'a'}}, '16': 'a'}}
I need to extract these dictionaries as ordered dictionaries as:
{'7': {'16': 'a', '15': {'10': {'9': {'8': 'a'}}, '12': {'11': 'a'}, '14': {'13': 'a'}}, '6': {'3': {'1': 'a', '2': 'a'}, '5': 'a', '4': 'a'}}}
This is what I tried but it didn't work.
>>> from collections import OrderedDict as od
>>> od(dic.strip())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/collections.py", line 52, in __init__
self.__update(*args, **kwds)
File "/usr/lib/python2.7/_abcoll.py", line 547, in update
for key, value in other:
ValueError: need more than 1 value to unpack
Is there any way to extract these dictionaries as ordered dictionaries. Any help will be appreciated.