我想在下面的词典中总结所有属于“sales”的数字:
{'a': {'sales': {}, 'revenue': {}}, 'b': {'sales': {}, 'revenue': {}}, 'c': {'sales': {'February2017': 6240.0, 'March2017': 8869.75, 'January2017': 15720.0}, 'revenue': {'February2017': 312.0, 'March2017': 432.4, 'January2017': 786.0}}, 'd': {'sales': {'February2017': 4184.9, 'March2017': 6181.709999999999, 'January2017': 6080.55}, 'revenue': {'February2017': 188.86, 'March2017': 292.61, 'January2017': 273.45}}}
#
输出应为:6240 + 8869.75 + 15720 + 4184.9 + 6181.7099 + 6080.55
我可以逐个循环显示键并获得正确的答案但是有更有效的方法吗?
total_sum = 0
for key,value in dict.items():
for key_a, value_a in value['sales'].items():
total_sum += value_a
例如,有没有办法可以通过reduce
?
由于
答案 0 :(得分:3)
为什么reduce()
可以sum()
使用生成器表达式,例如:
>>> sum(sum(value['sales'].values()) for value in data.values())
47276.91
或者以嵌套形式:
>>> sum(n for value in data.values() for n in value['sales'].values())
47276.91
注意:您不应该调用变量dict
,因为它隐藏了python的内置dict
类型。
答案 1 :(得分:0)
当前解决方案硬编码为给定的样本输入。这是一种递归方法,适用于任意结构化字典。
def recursiveSum(data):
count = 0
if not data:
return count
elif "sales" in data:
for k in data["sales"]:
if isinstance(data["sales"][k], dict):
count += recursiveSum(data["sales"][k])
else:
count += data["sales"][k]
else:
for k in data:
count += recursiveSum(data[k])
return count
而且,这输出:
>>> data = {'a': {'sales': {}, 'revenue': {}}, 'b': {'sales': {}, 'revenue': {}}, 'c': {'sales': {'February2017': 6240.0, 'March2017': 8869.75, 'January2017': 15720.0}, 'revenue': {'February2017': 312.0, 'March2017': 432.4, 'January2017': 786.0}}, 'd': {'sales': {'February2017': 4184.9, 'March2017': 6181.709999999999, 'January2017': 6080.55}, 'revenue': {'February2017': 188.86, 'March2017': 292.61, 'January2017': 273.45}}}
>>> print(recursiveSum(data))
47276.91
这种方法的优点是它适用于任何深度的嵌套。