Python|嵌套字典中每个键的总和值
给定一个嵌套字典,我们必须在该嵌套字典中找到特定值的总和。这在我们得到一个 JSON 对象或者我们已经抓取了一个特定页面并且我们想要对对象中特定属性的值求和的情况下基本上很有用。
代码 #1:使用 sum()函数查找锐度值的总和
# Python code to find sum values within nested dictionaries
weapons = {'': None, 'sword': { 'steel': 151,
'sharpness': 100,
'age': 2,},
'arrow': {'steel': 120,
'sharpness': 205,
'age': 1,}}
sumValue1 = sum(d['sharpness'] for d in weapons.values() if d)
sumValue2 = sum(d['steel'] for d in weapons.values() if d)
print(sumValue1)
print(sumValue2)
输出:
305
271
代码 #2:使用迭代将其转换为键:值对。
# Python code to find sum values within nested dictionaries
weapons = {'': None, 'sword': { 'steel': 151,
'sharpness': 100,
'age': 2,},
'arrow': {'steel': 120,
'sharpness': 205,
'age': 1,}}
sum = 0
# iterating key value pair
for key ,value in weapons.items():
if value and 'sharpness' in value.keys():
# Adding value of sharpness to sum
sum += value['sharpness']
# printing sum
print(sum)
输出:
305