如何从嵌套列表和字典中读取字典键和值

时间:2019-05-31 09:26:34

标签: python pandas

我有以下带有嵌套字典和列表的字典,试图输出所有键“ name”的值。 我不知道要在这本字典上实现的逻辑

期望输出类似

test
inside_test
inner_group1
GetFTP

词典数据:

{
  "id": "0ce8df69-016b-1000-ffff-ffffbe50cb53",
  "name": "test",
  "processGroupStatusSnapshot": {
    "name": "test",
    "connectionStatusSnapshots": [],
    "processorStatusSnapshots": [],
    "processGroupStatusSnapshots": [
      {
        "id": "0ce90089-016b-1000-ffff-ffffadb84af5",
        "processGroupStatusSnapshot": {
          "name": "inside_test",
          "connectionStatusSnapshots": [],
          "processorStatusSnapshots": [],
          "processGroupStatusSnapshots": [
            {
              "id": "0ce97287-016b-1000-0000-000056414ae7",
              "processGroupStatusSnapshot": {
                "id": "0ce97287-016b-1000-0000-000056414ae7",
                "name": "inner_group1",
                "connectionStatusSnapshots": [],
                "processorStatusSnapshots": [
                  {
                    "id": "0ce9ca47-016b-1000-0000-0000496a342d",
                    "processorStatusSnapshot": {
                      "id": "0ce9ca47-016b-1000-0000-0000496a342d",
                      "groupId": "0ce97287-016b-1000-0000-000056414ae7",
                      "name": "GetFTP"
                    }
                  }
                ],
                "processGroupStatusSnapshots": [],
                "remoteProcessGroupStatusSnapshots": [],
                "inputPortStatusSnapshots": [],
                "outputPortStatusSnapshots": []
              }
            }
          ]
        }
      }
    ]
  }
}

1 个答案:

答案 0 :(得分:1)

鉴于嵌套以及键名在所有级别上都将保持不变的事实,我认为递归解决方案将在此处最有效。请随时使用此解决方案作为参考,并根据需要进行修改。

参数d是这里的字典。

def find_name(d):
    if 'processGroupStatusSnapshot' in d:
        print("Name =", d['processGroupStatusSnapshot']['name'])
        nxt = d['processGroupStatusSnapshot']['processGroupStatusSnapshots']
        if len(nxt) > 0:
            find_name(nxt[0])

find_name(d)