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

Time:05-12

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related