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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s