我有一组数据,有一个字典数据如下
b = {
1: {
11: {
111: 150,
112: 151,
113: 152,
},
12: {
121: 160,
122: 161,
123: 162,
},
},
2: {
21: {
211: 0,
212: 1,
213: 1,
},
22: {
211: 0,
212: 1,
213: 1,
},
},
}
现在我需要一个方法,实现这样一个功能,随便传入一个key,返回该key下面所有子key的数据累计额和,如果该key是最后一级则返回该key值,如果没有改key值,则返回None
勉强算是实现了,需要进行更多样本测试
def custom_sum(obj):
"""
返回一个嵌套字典的所有值的和
:param obj: dict or int
:return: summary
"""
if isinstance(obj, dict):
summary = 0
for v in obj.values():
summary += custom_sum(v)
return summary
else:
return obj
def search(dic: dict, key: int):
"""
指定键进行多层嵌套的字典搜索
"""
if not isinstance(dic, dict):
return None
print("Current dict:")
print(dic)
value = dic.get(key)
if value:
return custom_sum(value)
else:
for v in dic.values():
result = search(v, key)
if result:
return result
return None
# print(search(b, 1111))
# print(search(b, 111))
# print(search(b, 11))
print(search(b, 1))
我和楼上的理解不一样,不知道对不对?
b = {
1: {
11: {
111: 150,
112: 151,
113: 152,
},
12: {
121: 160,
122: 161,
123: 162,
},
},
2: {
21: {
211: 0,
212: 1,
213: 1,
},
22: {
211: 0,
212: 1,
213: 1,
},
},
}
def find_key(key):
for item in b:
if key == item:
res = 0
for z1 in b[item]:
res += z1
return res
for a in b[item]:
if key == a:
res = 0
for z2 in b[item][a]:
res += z2
return res
for c in b[item][a]:
if key == c:
res = b[item][a][c]
return res
return None
if __name__ == '__main__':
res = find_key(12)
print(res)
运行结果
366
描述不清,子key 包括孙子节点key吗?输入的key 如果字典里有重复从哪一层算起?