@
@
@bickford2018-07-16 16:04:14
Python
@bickford, 2018-07-16 16:04:14

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

How to get a dictionary with the key INeedThisDict? Moreover, the source dictionary can be of different nesting, so it is impossible to take the value by index, because the desired dictionary may already be in another place.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan., 2018-07-16
_

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

For check:
Resp = dict()
Resp["abc"] = dict()
Resp["2"] = dict()
Resp["abc"]["find"] = 1
Resp["2"]["find_1"] = 2

print(find_key(Resp, "find_1"))

result 2.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question