现在有某个字典需要查询某个键的值
但是字典有嵌套字典,又嵌套列表。
所以写了个查询函数,该函数使用递归求值,多个相同的值也能返回,返回类型为列表
def find_disc(will_find_dist,find_keys):#will_find_dist要查找的字典,find_keys要查找的keys
value_found=[]
if(isinstance(will_find_dist,(list))):#含有列表的值处理
if (len(will_find_dist)>0):
for now_dist in will_find_dist:
found=find_disc(now_dist,find_keys)
if(found):
value_found.extend(found)
return value_found
if(not isinstance(will_find_dist,(dict))):#没有字典类型的了
return 0
else:#查找下一层
dict_key=will_find_dist.keys()
#print (dict_key)
for i in dict_key:
if(i==find_keys):
value_found.append(will_find_dist[i])
found=find_disc(will_find_dist[i],find_keys)
if(found):
value_found.extend(found)
return value_found
返回值为一个列表
例如
def find_disc(will_find_dist, find_keys): # will_find_dist要查找的字典,find_keys要查找的keys,found找到值存放处
value_found = []
if(isinstance(will_find_dist, (list))): # 含有列表的值处理
if (len(will_find_dist) > 0):
for now_dist in will_find_dist:
found = find_disc(now_dist, find_keys)
if(found):
value_found.extend(found)
return value_found
if(not isinstance(will_find_dist, (dict))): # 没有字典类型的了
return 0
else: # 查找下一层
dict_key = will_find_dist.keys()
#print (dict_key)
for i in dict_key:
if(i == find_keys):
value_found.append(will_find_dist[i])
found = find_disc(will_find_dist[i], find_keys)
if(found):
value_found.extend(found)
return value_found
a = {'A': {'A1': {'B': {'B1': ['b1', 'b2', 'b3'],
'B2': ['d1', 'd2', 'd3', {'n4': 'ccc2'}]},
'C': {'C1': ['a1', 'a2', 'a3'],
'C2': ['n1', {'n2': 'aaaa'}, {'n3': 'bbbb'}, {'n4': 'ccc'}],
'C3': ['x1', 'x2', 'x3', 'x4']}}}}
print(find_disc(a, 'n2'))
print(find_disc(a, 'C1'))
print(find_disc(a, 'n3'))
print(find_disc(a, 'n4'))
输出如下
[‘aaaa’]
[[‘a1’, ‘a2’, ‘a3’]]
[‘bbbb’]
[‘ccc2’, ‘ccc’]