Python – 字典中自定义嵌套键的总和
给定带有键作为嵌套字典的字典,找到嵌套字典中某些自定义键的值的总和。
Input : test_dict = {‘Gfg’ : {1 : 6, 5: 9, 9: 12}, ‘is’ : {1 : 9, 5: 7, 9: 2}, ‘best’ : {1 : 3, 5: 4, 9: 14}}, sum_key = [1]
Output : 18
Explanation : 6 + 9 + 3 = 18, only values with key 1 are summed.
Input : test_dict = {‘Gfg’ : {1 : 6, 5: 9, 9: 12}, ‘is’ : {1 : 9, 5: 7, 9: 2}, ‘best’ : {1 : 3, 5: 4, 9: 14}}, sum_key = [5, 9]
Output : 48
Explanation : Keys 5, 9 are summed.
方法#1:循环
这是可以解决此问题的粗暴方式。在此,我们对所有列表元素使用循环,并不断更新所有嵌套字典的总和值。
Python3
# Python3 code to demonstrate working of
# Summation of Custom nested keys in Dictionary
# Using loop
# initializing dictionary
test_dict = {'Gfg' : {1 : 6, 5: 9, 9: 12},
'is' : {1 : 9, 5: 7, 9: 2},
'best' : {1 : 3, 5: 4, 9: 14}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing sum keys
sum_key = [1, 9]
sum = 0
for ele in sum_key:
for key, val in test_dict.items():
# extracting summation of required values
sum = sum + val[ele]
# printing result
print("The required summation : " + str(sum))
Python3
# Python3 code to demonstrate working of
# Summation of Custom nested keys in Dictionary
# Using list comprehension + sum()
# initializing dictionary
test_dict = {'Gfg' : {1 : 6, 5: 9, 9: 12},
'is' : {1 : 9, 5: 7, 9: 2},
'best' : {1 : 3, 5: 4, 9: 14}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing sum keys
sum_key = [1, 9]
# sum() used to get cumulative summation
res = sum([val[ele] for ele in sum_key for key, val in test_dict.items()])
# printing result
print("The required summation : " + str(res))
The original dictionary is : {‘Gfg’: {1: 6, 5: 9, 9: 12}, ‘is’: {1: 9, 5: 7, 9: 2}, ‘best’: {1: 3, 5: 4, 9: 14}}
The required summation : 46
方法 #2:使用列表理解 + sum()
上述功能的组合也可以用来解决这个问题。在此,我们使用 sum() 执行求和任务,其余逻辑也使用列表理解封装为单行。
Python3
# Python3 code to demonstrate working of
# Summation of Custom nested keys in Dictionary
# Using list comprehension + sum()
# initializing dictionary
test_dict = {'Gfg' : {1 : 6, 5: 9, 9: 12},
'is' : {1 : 9, 5: 7, 9: 2},
'best' : {1 : 3, 5: 4, 9: 14}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing sum keys
sum_key = [1, 9]
# sum() used to get cumulative summation
res = sum([val[ele] for ele in sum_key for key, val in test_dict.items()])
# printing result
print("The required summation : " + str(res))
The original dictionary is : {‘Gfg’: {1: 6, 5: 9, 9: 12}, ‘is’: {1: 9, 5: 7, 9: 2}, ‘best’: {1: 3, 5: 4, 9: 14}}
The required summation : 46