geoffroygivry
10/8/2017 - 11:13 AM

nested keys in dictionary

def find(key, dictionary):
    for k, v in dictionary.items():
        if k == key:
            yield v
        elif isinstance(v, dict):
            for result in find(key, v):
                yield result
        elif isinstance(v, list):
            for d in v:
                for result in find(key, d):
                    yield result

example = {
    "_id": {
        "$oid": "59d55763e1382315035d1649"
    },
    "show": "RBY",
    "name": "awning01",
    "target_date": "2017-10-23T18:00:00.000000",
    "hero": False,
    "type": "3D",
    "tasks": [
        {
            "task": "MOD",
            "assignee": "Geoffroy",
            "status": "IN-PROGRESS",
            "task_target_date": "2017-06-10T18:05:19.197000",
            "published": {
                "latest": "RBY_awning01_MOD_v01_2017-10-04T22:43:43.17900"

            }
        }
    ]
}

final_result = list(find('latesst', example))
if len(final_result) == 1 : 
    print(final_result[0])
elif len(final_result) == 0:
    print("nothing in it")
else:
    print(final_result)