在Python中递归遍历字典?

时间:2014-04-09 02:44:14

标签: python recursion dictionary lambda list-comprehension

递归遍历字典的更好方法是什么? 我可以用lambda或/和列表推导来做吗?

我有:

[
  {
    "id": 1,
    "children": [
      {
        "id": 2,
        "children": []
      }
    ]
  },
  {
    "id": 3,
    "children": []
  },
  {
    "id": 4,
    "children": [
      {
        "id": 5,
        "children": [
          {
            "id": 6,
            "children": [
              {
                "id": 7,
                "children": []
              }
            ]
          }
        ]
      }
    ]
  }
]

我想:

[1,2,3,4,5,6,7]

3 个答案:

答案 0 :(得分:3)

最简单的方法是使用递归函数:

recursive_function = lambda x: [x['id']] + [item for child in x['children'] for item in recursive_function(child)]
result = [item for topnode in whatever_your_list_is_called for item in recursive_function(topnode)]

答案 1 :(得分:3)

您可以使用此通用生成器函数递归遍历您的词典,如此

def rec(current_object):
    if isinstance(current_object, dict):
        yield current_object["id"]
        for item in rec(current_object["children"]):
            yield item
    elif isinstance(current_object, list):
        for items in current_object:
            for item in rec(items):
                yield item

print list(rec(data))
# [1, 2, 3, 4, 5, 6, 7]

答案 2 :(得分:0)

我的解决方案:

results = []
def function(lst):
    for item in lst:
        results.append(item.get('id'))
        function(item.get('children'))
function(l)
print results

[1,2,3,4,5,6,7]