Quick Post: Recursive Function to Search Multi-Level Dictionary

Many¬†APIs return JSON that is converted into a multilevel dictionary (e.g. EPO OPS). The following code snippet helps find a key (e.g. “id”) that is nested within the dictionary.

The function is based on this answer. To find more than the first occurrence “return” may be converted to “yield”.

def keysearch(d, key):
    """Recursive function to look for first occurrence of key in multi-level dict. 
    param dict d: dictionary to process
    param string key: key to locate"""
 
    if isinstance(d, dict):
        if key in d:
            return d[key]
        else:
            if isinstance(d, dict):
                for k in d:
                    found = keysearch(d[k], key)
                    if found:
                        return found
            else:
                if isinstance(d, list):
                    for i in d:
                        found = keysearch(d[k], key)
                        if found:
                            return found