我有一个python嵌套字典,正在尝试将字典的每个级别包装在一个列表中。原因是该词典正在转换为Java Script对象,并且我正在尝试维护词典的顺序。我已经举了一个我想做的事的例子。非常感谢您提供帮助。
输入:
myDict = {
'outerkey1': {'innerkey1': 1,
'innerkey2': 2,
'innerkey3': 3,
'innerkey4': 4,
'innerkey5': 5,
'innerkey6': 6,
'innerkey7': 7,
'innerkey8': 8,
'innerkey9': 9,
'innerkey10': 10,
'innerkey11': 11},
'outerkey2': {'innerkey1': 100,
'innerkey2': 200,
'innerkey3': 300,
'innerkey4': 400,
'innerkey5': 500,
'innerkey6': 600,
'innerkey7': 700,
'innerkey8': 800,
'innerkey9': 900,
'innerkey10': 1000,
'innerkey11': 1100}
}
尝试:
# my thought to change nested dict to nested list
dictToList = [[k, v] for k, v in myDict.items()]
# return result is only changing the outer part
# of the dict to list but not the inner part
#
[['outerkey1', {'innerkey11': 11, 'innerkey8': 8, 'innerkey4': 4, 'innerkey1': 1, 'innerkey6': 6, 'innerkey7': 7, 'innerkey2': 2, 'innerkey9': 9, 'innerkey5': 5, 'innerkey3': 3, 'innerkey10': 10}], ['outerkey2', {'innerkey11': 1100, 'innerkey8': 800, 'innerkey4': 400, 'innerkey1': 100, 'innerkey6': 600, 'innerkey7': 700, 'innerkey2': 200, 'innerkey9': 900, 'innerkey5': 500, 'innerkey3': 300, 'innerkey10': 1000}]]
我正在尝试实现的示例架构。
myDict = [
[{'outerkey2': [
{'innerkey1': 100,
'innerkey10': 1000,
'innerkey11': 1100,
'innerkey2': 200,
'innerkey3': 300,
'innerkey4': 400,
'innerkey5': 500,
'innerkey6': 600,
'innerkey7': 700,
'innerkey8': 800,
'innerkey9': 900}
]
}],
[{'outerkey1': [
{'innerkey1': 1,
'innerkey10': 10,
'innerkey11': 11,
'innerkey2': 2,
'innerkey3': 3,
'innerkey4': 4,
'innerkey5': 5,
'innerkey6': 6,
'innerkey7': 7,
'innerkey8': 8,
'innerkey9': 9}
]
}]
]
答案 0 :(得分:1)
根据您想要的结果,您可以执行以下操作:
myDict = [[{k : [myDict[k]]}] for k in myDict.keys()]
这将为您提供:
[[{'outerkey2': [{'innerkey11': 1100, 'innerkey3': 300, 'innerkey2': 200, 'innerkey6': 600, 'innerkey10': 1000, 'innerkey8': 800, 'innerkey4': 400, 'innerkey5': 500, 'innerkey1': 100, 'innerkey9': 900, 'innerkey7': 700}]}], [{'outerkey1': [{'innerkey11': 11, 'innerkey3': 3, 'innerkey2': 2, 'innerkey6': 6, 'innerkey10': 10, 'innerkey8': 8, 'innerkey4': 4, 'innerkey5': 5, 'innerkey1': 1, 'innerkey9': 9, 'innerkey7': 7}]}]]