Python 向现有嵌套字典(树)添加级别

Python 向现有嵌套字典(树)添加级别,python,list,dictionary,Python,List,Dictionary,我有一个带有给定值的嵌套字典树 nodes = [{'id': 20, 'child': [{'id': 21, 'child': [{'id': 23, 'child': [{'id': 31}]}, {'id': 24}]}, {'id': 22}]}, {'id': 25, 'child': [{'id': 32}]}] 我喜欢用新的key和valuelevel更新它:每个dicitonary中的integer。 级别应指定嵌套顺序。如下所示 nodes = [{'id': 20, 'c

我有一个带有给定值的嵌套字典树

nodes = [{'id': 20, 'child': [{'id': 21, 'child': [{'id': 23, 'child': [{'id': 31}]}, {'id': 24}]}, {'id': 22}]}, {'id': 25, 'child': [{'id': 32}]}]
我喜欢用新的key和valuelevel更新它:每个dicitonary中的integer。 级别应指定嵌套顺序。如下所示

nodes = [{'id': 20, 'child': [{'id': 21, 'child': [{'id': 23, 'child': [{'id': 31}], 'level': 2}, {'id': 24}], 'level': 1}, {'id': 22}], 'level': 0}, {'id': 25, 'child': [{'id': 32}], 'level': 3}]
我试图通过使用递归得到解决方案。但由于for循环,此解决方案是不正确的

counter=0
def abc(list):
    global counter
    for i in list:
        if 'level' not in list:
            if 'child' in i:
                i.update(level=counter)
                counter += 1
                abc(i['child'])
    return list

您可以使用递归来实现这一点:

nodes = [{'id': 20, 'child': [{'id': 21, 'child': [{'id': 23, 'child': [{'id': 31}]}, {'id': 24}]}, {'id': 22}]}, {'id': 25, 'child': [{'id': 32}]}]

def set_level(obj, level=0):
    if isinstance(obj, list):
        # If the function is called on a list, we call the function on each element
        return [set_level(el) for el in obj]
    if isinstance(obj, dict):
        # If the function in called on a dict, we add the level
        obj['level'] = level
        if "child" in obj:
            # If the object have a sublevel, we call the function
            # for this sublevel
            obj["child"] = [set_level(c, level=level+1) for c in obj["child"]]
        return obj


nodes = set_level(nodes)
这将是输出:

[
  {
    "child": [
      {
        "child": [
          {
            "child": [
              {
                "id": 31,
                "level": 3
              }
            ],
            "id": 23,
            "level": 2
          },
          {
            "id": 24,
            "level": 2
          }
        ],
        "id": 21,
        "level": 1
      },
      {
        "id": 22,
        "level": 1
      }
    ],
    "id": 20,
    "level": 0
  },
  {
    "child": [
      {
        "id": 32,
        "level": 1
      }
    ],
    "id": 25,
    "level": 0
  }
]

为什么错了?显示代码返回的内容和预期返回的内容如果我理解您的要求,在返回列表之前添加一个计数器-=1将使级别正确。但我不知道你到底想要什么