Python|字典中键的值求和
使用Python字典可以进行许多操作,例如分组和转换。但有时,我们也会遇到需要对字典列表中键的值进行聚合的问题。此任务在日常编程中很常见。让我们讨论可以执行此任务的某些方式。
方法 #1:使用sum()
+ 列表推导
这是一种单线方法,用于执行获取特定键总和的任务,同时使用列表理解迭代到字典列表中的相似键。
# Python3 code to demonstrate working of
# Value summation of key in dictionary
# Using sum() + list comprehension
# Initialize list
test_list = [{'gfg' : 1, 'is' : 2, 'best' : 3},
{'gfg' : 7, 'is' : 3, 'best' : 5},
{'gfg' : 9, 'is' : 8, 'best' : 6}]
# printing original list
print("The original list is : " + str(test_list))
# Value summation of key in dictionary
# Using sum() + list comprehension
res = sum(sub['gfg'] for sub in test_list)
# printing result
print("The sum of particular key is : " + str(res))
输出 :
The original list is : [{‘best’: 3, ‘gfg’: 1, ‘is’: 2}, {‘best’: 5, ‘gfg’: 7, ‘is’: 3}, {‘best’: 6, ‘gfg’: 9, ‘is’: 8}]
The sum of particular key is : 17
方法 #2:使用sum() + itemgetter() + map()
这些功能的组合也可用于执行此任务。在此,主要区别在于理解任务由map()
完成,而密钥访问任务由itemgetter().
# Python3 code to demonstrate working of
# Value summation of key in dictionary
# Using sum() + itemgetter() + map()
import operator
# Initialize list
test_list = [{'gfg' : 1, 'is' : 2, 'best' : 3},
{'gfg' : 7, 'is' : 3, 'best' : 5},
{'gfg' : 9, 'is' : 8, 'best' : 6}]
# printing original list
print("The original list is : " + str(test_list))
# Value summation of key in dictionary
# Using sum() + itemgetter() + map()
res = sum(map(operator.itemgetter('gfg'), test_list))
# printing result
print("The sum of particular key is : " + str(res))
输出 :
The original list is : [{‘best’: 3, ‘gfg’: 1, ‘is’: 2}, {‘best’: 5, ‘gfg’: 7, ‘is’: 3}, {‘best’: 6, ‘gfg’: 9, ‘is’: 8}]
The sum of particular key is : 17