Answer the question
In order to leave comments, you need to log in
How to get a dictionary with a certain key from a mass of nested dictionaries?
Greetings. I get a dictionary like this:
{
"data": {
"FirstKey": {
"SecondKey": {
"AnyKey": "something",
"AnyKey2": "something",
"AnyKey3": "something",
"Body": {
"Response": {
"Result": {
"Xxx": {
"Any": "true"
},
"Zzz": {
"Bool": "true"
},
"INeedThisDict": {
"SomeInfo": "true"
"SomeInfo2": {
"Key": "Value",
"Key2": "Value2",
},
},
"Yyy": "000",
"Ccc": "111",
"Status": "200",
"Error": "no"
}
}
}
}
}
}
Answer the question
In order to leave comments, you need to log in
You can go recursively through the dictionary until the first match, because there is no guarantee that the same key cannot be at different levels.
For example like this:
def find_key(dct, key):
try:
if dct.get(key):
return dct[key]
else:
for k in dct.values():
val = find_key(k, key)
if val:
return val
except:
return
Resp = dict()
Resp["abc"] = dict()
Resp["2"] = dict()
Resp["abc"]["find"] = 1
Resp["2"]["find_1"] = 2
print(find_key(Resp, "find_1"))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question