亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

紅顏莎娜 2023-12-05 15:34:42
我從 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# Worksrecursive_lookup("Ergebnis", jsondata)# Returns Nonerecursive_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)
查看完整描述

1 回答

?
茅侃侃

TA貢獻1842條經驗 獲得超21個贊

遞歸函數根據鍵字段在嵌套字典中查找值


代碼


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


查看完整回答
反對 回復 2023-12-05
  • 1 回答
  • 0 關注
  • 140 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號