对于字典:d = {1:1, 2:2, 3:{4:44, 5:55, 6:{7:{7:1024}, 8:88}}, 9:9 }
1.如何获取到{7:1024}中的1024?
2.如何获取到所有key为7的value值?
方法一: 直接输出
d = {1:1, 2:2, 3:{4:44, 5:55, 6:{7:{7:1024}, 8:88}}, 9:9 }
print("{7:1024}中的1024:",d[3][6][7][7])
print("所有key为7的value值:", d[3][6][7],d[3][6][7][7])

这种方法一般不使用
方法二: 递归遍历
d = {1:1, 2:2, 3:{4:44, 5:55, 6:{7:{7:1024}, 8:88}}, 9:9 }
def get_dict_value(now_dict, target_key, results=[]):
for key in now_dict.keys(): # 当前迭代的字典
data = now_dict[key] # 当前key所对应的value赋给data
if isinstance(data, dict): # 如果data是一个字典,就递归遍历
get_dict_value(data, target_key, results=results)
if key==target_key and isinstance(data, dict) != True: # 找到了目标key,并且它的value不是一个字典
results.append(now_dict[key])
return results
res = get_dict_value(d, 7, results=[])
print(res)
获取所有key为7的value值:
if key==target_key:
results.append(now_dict[key])
输出结果:

本文介绍了如何遍历Python中的嵌套字典,包括如何获取特定路径的值,如1024,以及如何获取所有key为7的value。提供了直接输出和递归遍历两种方法。
1051

被折叠的 条评论
为什么被折叠?



