'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



Solution 1:[1]

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

Solution 2:[2]

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.

Solution 3:[3]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TheRavenSpectre
Solution 2 I break things
Solution 3 Brijal Kansara