【发布时间】:2015-08-05 10:10:12
【问题描述】:
如何保留嵌套字典的输入顺序?具体来说:我使用另一个字典使其成为有序字典(名为“outdict”)的嵌套字典,然后添加新键。
示例数据:
example1 = {'x': '28', 'y': 9,'z': '1999'}
example2 = {'x': '12', 'y': 15,'z': '2000'}
test1 = "abc"
test2 = "def"
我想要的“判决”形式是
{'one': {'x': '28', 'y': 9,'z': '1999', 'alpha': 'abc'},
'two': {'x': '12', 'y': 15,'z': '2000', 'alpha': 'def'}}
我尝试了两件事:
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
(来自https://stackoverflow.com/questions/18809482#18809656) 结果:未排序
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
结果:未排序
【问题讨论】:
标签: python dictionary nested