如何从嵌入的字典/列表中提取所有值

时间:2018-01-22 05:47:20

标签: python python-3.x dictionary recursion key-value

我们说我们有以下内容......

pract={
  "hello": {
    "more": 1,
    "some": 2,
    "yes": [
      {
        "dicct": 1
      },
      {
        "more_dict": 4
      }
    ]
  }
}

我有一个嵌入式dict/list。我需要获得所有单一值。所以在这种情况下,我的结果将是......

[1, 2, 1, 4]

理想情况下,我想保留直接父母,所以这会更好......

[("more",1), ("some",2), ("dicct", 1), ("more_dict", 4)]

这是我的递归尝试......

def grab_children(father, result):
    if type(father) == type([]):
        for e in father:
            if isinstance(e, dict):
                grab_children(e, result)
    else:
        for child_key, child_value in father.items():
            if isinstance(child_value, dict):
                grab_children(child_value, result)
            else:
                result.append((child_key, child_value))

我这样跑...

child = []
grab_children(pract, child)

但是当我打印子数组时,我得到......

[('more', 1), ('some', 2), ('yes', [{'dicct': 1}, {'more_dict': 4}])]

显然不是我想要的输出。我的解决方案出了什么问题?

1 个答案:

答案 0 :(得分:1)

enter image description here适用于此类事情:

代码:

def get_terminal_nodes(data):
    if isinstance(data, list):
        for item in data:
            for i in get_terminal_nodes(item):
                yield i

    elif isinstance(data, dict):
        for k, item in data.items():
            if isinstance(item, (list, dict)):
                for i in get_terminal_nodes(item):
                    yield i
            else:
                yield k, item

测试代码:

pract = {
    "hello": {
        "more": 1,
        "some": 2,
        "yes": [{"dicct": 1}, {"more_dict": 4}]}
}

flat_data = dict(get_terminal_nodes(pract))
print(flat_data)

结果:

{'more': 1, 'some': 2, 'dicct': 1, 'more_dict': 4}