python从多级字典中,获取给定key对应的值,获取给定key所在的路径

本文介绍了一种在Python中遍历多级字典的方法,通过递归查找指定键并记录其路径,适用于复杂的数据结构搜索场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 python从多级字典中,获取给定key对应的值,获取给定key所在的路径

其实就是个多叉树遍历,并获取相应值的路径

 

# coding=utf8
'''
date: 2019/01/30
powered by guanrongjia
all rights reserved

ability:
this demo show you how to scan  a dict to find the value that you given.
it records the value and the router of zhe key you given .
there are a lot of ways to realize it,
hrer is just one way ,
enjoy coding!

if there is any thing you want to communicate with me ,
leave message in my git:
https://github.com/guanrongjia/find-route-multilevel-dict
'''
import copy


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

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


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 test_fun():
    '''
    this function show you how to use and test your program.
    :return:
    '''
    key_list = ['TASKBAR', 'WINKEY', 'CLOUDMUSIC', 'POWER', 'POWER_OPTIONS', 'DESKTOP', 'THIS_PC', 'TUDOU',
                '', None, 0, 'no_match_str'
                ]
    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__':
    test_fun()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值