How can I preserve the input order of nested dictionaries? Specifically: I use another dictionary to make it the nested dictionary of an ordered dict (named 'outdict'), and then I add new keys.
Example data:
example1 = {'x': '28', 'y': 9,'z': '1999'}
example2 = {'x': '12', 'y': 15,'z': '2000'}
test1 = "abc"
test2 = "def"
My desired form of 'outdict' is
{'one': {'x': '28', 'y': 9,'z': '1999', 'alpha': 'abc'},
'two': {'x': '12', 'y': 15,'z': '2000', 'alpha': 'def'}}
I tried two things:
1.
from collections import OrderedDict
class MyDict(OrderedDict):
def __missing__(self, key):
val = self[key] = MyDict()
return val
outdict = MyDict()
outdict["one"].update(OrderedDict(example1))
outdict["one"]["alpha"] = test1
outdict["two"].update(OrderedDict(example2))
outdict["two"]["alpha"] = test2
(from http://stackoverflow.com/questions/18809482#18809656) Result: Not sorted
2.
outdict = OrderedDict()
outdict["one"] = OrderedDict()
outdict["two"] = OrderedDict()
outdict["one"].update(OrderedDict(example1))
outdict["one"]["alpha"] = test1
outdict["two"].update(OrderedDict(example2))
outdict["two"]["alpha"] = test2
Result: Not sorted