python 简单递归返回字典树搜索的路径(键)

字典长这样

a = {
    
    "head_class":145,

"next_class":{
    
    "head_class":987, 

		"next_class":{
    
    "head_class": 666, 

	"next_class" : None} 
 				}  
	}

在这里插入图片描述
现在要输入head_class = 666,与字典a,查找到得到head_class = 666的路径(键),如下的期望结果

a["next_class"]["next_class"]["head_class"]

以下为具体代码,注意这里因为每层的键都是一样的head_class和next_class,所以每层不一样的话,需要对 tem_next_class_string的取值的部分,进行重写re_key方法


head_class_string = ""

def re_key(tem_dict , val, previous_key):
    """用于返回字典最内层["head_class"]与val 匹配的,路径值"""
    """输入需要搜寻的字典,匹配的值"""
    global head_class_string

    for key in tem_dict:

        tem_head_class_string = "tem_dict" +  previous_key + '["head_class"]'

        if key == "next_class":

            key_string =  str(previous_key) + '["' + key + '"]'
            tem_next_class_string = "tem_dict" + key_string
            # print(tem_next_class_string)

            if eval(tem_next_class_string) != None:

                re_key(tem_dict, val, key_string)

            else:
                print("遍历一层完毕,没有发现")

                #说明下级"head_class" 键值下,还有字典结构,继续通过递归进行搜查


        else:
            print(tem_head_class_string)
            print(eval(tem_head_class_string))


            if eval(tem_head_class_string) == val:
                head_class_string = tem_head_class_string
                # print("6"*200)
                # print(tem_head_class_string)
                # return tem_head_class_string







a = {
    
    "head_class":145,"next_class":{
    
    "head_class":987, "next_class":{
    
    "head_class": 666, "next_class" : None}  }  }

re_key(a,666,"")
print("*"*100)
print(head_class_string)

# b = re_key(a,666,"")
#
# print("*"*100)
# print(b)
#
# print(type(b))

这里还有个需要注意的部分,因为是用的递归的方式,所以return在多次递归后,无法返回值到主函数调用的变量空间了,所以这里是用的全局变量来把值取出来的

输出

F:\aanaa\envs\planone\python.exe K:/python打包专用文件夹/new_old/cs.py
tem_dict["head_class"]
145
tem_dict["next_class"]["head_class"]
987
tem_dict["next_class"]["next_class"]["head_class"]
666
遍历一层完毕,没有发现
****************************************************************************************************
tem_dict["next_class"]["next_class"]["head_class"]

进程已结束,退出代码 0

猜你喜欢

转载自blog.csdn.net/weixin_43134049/article/details/115083791