【发布时间】:2020-06-11 02:08:23
【问题描述】:
我有一本看起来像这样的字典:
normalDictionary = {'a' : {'b': {}},
'a1': {'b1': {'c1' : {},
'd1' : {}}}}
我想将其反转,使其看起来像:
invertedDictionary = {'d1': {'b1': {'a1': {}}},
'c1': {'b1': {'a1': {}}},
'b': {'a': {}}}
那个 python 函数会是什么样子?
我似乎无法过去:
def invert_dictionary( node, leafName, indent ):
keys = list( node.keys() )
keys.sort()
constructed = { leafName: {} }
for key in keys:
inverted = invert_dictionary( node[ key ], key, indent + 4 )
return constructed
invertedDictionary = {}
for key in normalDictionary
inverted = invert_dictionary( normalDictionary[ key ], key, indent = 0 )
【问题讨论】:
-
您漂亮的打印顺序有点混乱。您可能希望确保相同的顺序。
-
字典越深入,缩进越多。
-
是的,但请查看
invertedDictionary = { ... }订单。底行首先打印得很漂亮。 -
漂亮的打印顺序无关紧要...仅用于演示目的。看看 normalDictionary 和 reverseDictionary。
-
是的,一分钟左右我就明白了;我只是担心其他可能想回答您问题的人。
标签: python algorithm dictionary recursion