我从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)
基于关键字字段在嵌套字典中查找值的递归函数
代码
用法
测试
相关问题 更多 >
编程相关推荐