在混合列表的嵌套字典中查找键

2024-10-03 00:25:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我从API获取JSON数据。数据集很大且嵌套。我可以像这样访问Datenreihen键:

jsondata.get("Ergebnis")[0].get("Kontakte").get("Datenreihen")

正如你所看到的,这是一个混合字典和列表

我尝试了以下方法,但对列表无效:-(

def recursive_lookup(k, d):
    if k in d:
        return d[k]
    for v in d.values():
        if isinstance(v, dict):
            return recursive_lookup(k, v)
    return None

# Works
recursive_lookup("Ergebnis", jsondata)

# Returns None
recursive_lookup("Datenreihen", jsondata)

无论我的对象嵌套得有多深,是否有一种简单的方法来访问和输入我的字典

以下是示例数据:

{
    "Success":true,
    "Ergebnis":[
       {
          "ErgA1a: KPI Zeitreihe":{
             "Message":"",
             "MitZielgruppe":true,
             "Beschriftung":[
                "2019 KW 27",
                "2019 KW 28",
                "2019 KW 29"
             ],
             "Datenreihen":{
                "Gesamt":{
                   "Name":"Sympathie [#4]\n(Sehr sympathisch, Sympathisch)",
                   "Werte":[
                      39.922142815641145,
                      37.751410794385762,
                      38.35504885993484
                   ]
                }
             }
          }
       }
    ],
    "rest":[
       {
          "test":"bla"
       }
    ]
 }

 data.get("ErgebnisseAnalyse")[0].get("ErgA1a: KPI Zeitreihe")

recursive_lookup("ErgA1a: KPI Zeitreihe", data)

Tags: 数据方法列表getreturn字典lookuprecursive
1条回答
网友
1楼 · 发布于 2024-10-03 00:25:36

基于关键字字段在嵌套字典中查找值的递归函数

代码

def find_item(obj, field):
    """
    Takes a dict with nested lists and dicts,
    and searches all dicts for a key of the field
    provided.
    """
    if isinstance(obj, dict):
        for k, v in obj.items():
            if k == field:
                yield v
            elif isinstance(v, dict) or isinstance(v, list):
                yield from find_item(v, field)
    elif isinstance(obj, list):
        for v in obj:
            yield from find_item(v, field)

用法

value = next(find_item(dictionary_object, field), None)

测试

# Nested dictionary
dic = {
    "a": [{"b": {"c": 1}},
          {"d": 2}],
     "e": 3}

# Values form various fields
print(next(find_item(dic, "a"), None))  # Output: [{'b': {'c': 1}}, {'d': 2}]
print(next(find_item(dic, "b"), None))  # Output: {'c': 1}
print(next(find_item(dic, "c"), None))  # Output: 1
print(next(find_item(dic, "d"), None))  # Output: 2
print(next(find_item(dic, "e"), None))  # Output: 3
print(next(find_item(dic, "h"), None))  # Output: None

相关问题 更多 >