Reputation: 101
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
Upvotes: 0
Views: 59
Reputation: 397
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"))
Upvotes: 1
Reputation: 191
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.
Upvotes: 0
Reputation: 326
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.
Upvotes: 0