我需要決議一些非常奇怪的 json 有效負載,但我完全卡住了..
假設我有一個嵌套字典,其中的串列如下所示:
test_dict1 = {
"blah":"blah",
"alerts": [{"test1":"1", "test":"2"}],
"foo": {
"foo":"bar",
"foo1": [{"test3":"3"}]
}}
有沒有一個函式可以給我 key 的值test3?或者更確切地說,第一次出現鍵的第一個值test3
編輯 我的意思是我可以搜索密鑰 test3 的功能,因為我主要關心密鑰并且我可以獲得的不同字典可能具有不同的結構
uj5u.com熱心網友回復:
就像訪問任何其他嵌套結構一樣訪問它:
test_dict1["foo"]["foo1"][0]["test3"]
另外,第一次出現是什么意思?字典沒有特定的順序,所以這對你沒什么用。
uj5u.com熱心網友回復:
如果您只想要 test3 的值,那么您可以通過以下方式獲得它,
test_dict1["foo"]["foo1"][0]["test3"]
但是,如果您想要動態價值,那么它將使用不同的方法來完成。看,當您使用字典和索引串列時,您可以使用鍵名。
uj5u.com熱心網友回復:
由于您不知道值的深度,因此建議使用遞回函式遍歷所有層直到找到它。我在下面使用了 DFS。
def search(ld, find):
if(type(ld)==list):
for i in ld:
if(type(i)==list or type(i)==dict):
result=search(i, find)
if(result!=None): return result
elif(type(ld)==dict):
try:
return ld[find]
except(KeyError):
for i in ld:
if(type(ld[i])==list or type(ld[i])):
result=search(ld[i], find)
if(result!=None): return result
else:
return None
test_dict1 = {
"blah":"blah",
"alerts": [{"test1":"1", "test":"2"}],
"foo": {
"foo":"bar",
"foo1": [{"test3":"3"}]
}}
print(search(test_dict1, "test3"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/473198.html
