python-获取dict的key 路径

有时候我们想获取key,这个好办直接遍历判断就行, 如果想获取key 在的路径 就显得比较麻烦,下边的演示就是获取key 路径, 核心思想是递归

import copy

demo_dect = {
    'TASKBAR': {
        'WINKEY': {
            'CLOUDMUSIC': 0
        },
        'POWER': {
            'POWER_OPTIONS': 0
        }

    },
    'DESKTOP': {
        'THIS_PC': {
            'TUDOU': 0,
'POWER_OPTIONS': 0

        }
    }
}
a=['TASKBAR', 'WINKEY', 'POWER', 'POWER_OPTIONS']
['TASKBAR', 'POWER', 'POWER_OPTIONS']


def find_by_exhaustion(input_key, current_dict, router):
    '''
    :param input_key:  the key you given
    :param current_dict: the dict you have to scan
    :param router: record your route to reach here
    :return:
    '''
    router = copy.deepcopy(router)
    for index, key in enumerate(current_dict):
        val = current_dict.get(key)
        if input_key == key:
            router.append(key)
            return val, router
        elif type(val) == type({}):
            router.append(key)
            result_tuple = find_by_exhaustion(input_key, val, router)
            if result_tuple:
                return result_tuple[0], result_tuple[1]
            else:
                if router:
                    router = router[0:len(router) -1]



def dtest_fun():
    '''
    this function show you how to use and test your program.
    :return:
    '''
    key_list = [ 'POWER_OPTIONS']
    for input_key in key_list:
        print ('*' * 25,)
        print (input_key,)
        print ('*' * 25)

        router = []
        result = find_by_exhaustion(input_key, demo_dect, router)
        if result:
            print( 'value:')
            print (result[0])
            print ('router:')
            print (result[1])


if __name__ == '__main__':
    dtest_fun()

你可能感兴趣的:(python3,高级进阶之路)