简体   繁体   中英

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

There's some very strange json payloads that I need to parse and I'm complete stuck..

Say I have a nested dictionary with lists that looks like this:

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

Is there a function that would be able to give me the value of the key test3 ? Or rather the first value for the first occurrence of the key test3

Edit What I meant was a function where I can search for the key test3, since I am mainly concerned about the key and the different dictionaries that I could get may have different structures

Since you do not know how deep inside the value is, it is prob advisable to use a recursive function to iterate through all the layers till it's found. I used DFS below.

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"))

Just access it like you would any other nested structure:

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

Also, what do you mean by the first occurrence? Dictionaries don't have a specific order, so that won't really do much for you.

If you only want the value of test3 then this is how you can get it,

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

But if you want value dynamically then it will be done with a different approch. See, you can use a key name when you are working with dictionaries and indexing when it comes to the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM