簡體   English   中英

如何在帶有列表的嵌套字典中查找鍵的值?

[英]How to find a value of a key in a nested dictionary with lists?

我需要解析一些非常奇怪的 json 有效負載,但我完全卡住了..

假設我有一個嵌套字典,其中的列表如下所示:

test_dict1 = {
    "blah":"blah", 
    "alerts": [{"test1":"1", "test":"2"}], 
    "foo": {
        "foo":"bar", 
        "foo1": [{"test3":"3"}]
        }}

有沒有一個函數可以給我 key test3的值? 或者更確切地說,第一次出現鍵test3的第一個值

編輯我的意思是我可以搜索密鑰 test3 的功能,因為我主要關心密鑰並且我可以獲得的不同字典可能具有不同的結構

由於您不知道值的深度,因此建議使用遞歸函數遍歷所有層直到找到它。 我在下面使用了 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"))

就像訪問任何其他嵌套結構一樣訪問它:

test_dict1["foo"]["foo1"][0]["test3"]

另外,第一次出現是什么意思? 字典沒有特定的順序,所以這對你沒什么用。

如果您只想要 test3 的值,那么您可以通過以下方式獲得它,

test_dict1["foo"]["foo1"][0]["test3"]

但是,如果您想要動態價值,那么它將使用不同的方法來完成。 看,當您使用字典和索引列表時,您可以使用鍵名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM