딕셔너리 키 값으로 상위 키 및 인덱스 path 가져오기

def keyPathChecker(dict_obj, key):
    result = []
    path = []
    from copy import copy


    def find_path(dict_obj, key, i=None):
        for k, v in dict_obj.items():
            path.append(k)
            if isinstance(v, dict):
                find_path(v, key, i)
            if isinstance(v, list):
                for i, item in enumerate(v):
                    path.append(i)
                    if isinstance(item, dict):
                        find_path(item, key, i)
                    path.pop()
            if k == key:
                result.append(copy(path))
            if path != []:
                path.pop()

    find_path(dict_obj, key)
    for pathList in result:
        keyPath = "dictOBJ"
        for pathElem in pathList:
            if isinstance(pathElem,str):
                keyPath+=f"['{pathElem}']"
            elif isinstance(pathElem,int):
                keyPath += f"[{pathElem}]"
        print(keyPath)

keyPathChecker(, '')

Leave a Comment