【问题标题】:Find key in nested dictionary mixed with lists在与列表混合的嵌套字典中查找键
【发布时间】:2020-10-20 14:46:48
【问题描述】:

我从 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)

【问题讨论】:

  • 你能举一个简单的例子来说明它不适用的数据吗?
  • 更新问题

标签: python dictionary recursion nested


【解决方案1】:

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

代码

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2019-03-18
    • 2012-04-06
    • 2021-10-20
    • 1970-01-01
    • 2022-01-06
    相关资源
    最近更新 更多