Python – 字典列表中的求和分组
有时,在使用Python字典时,我们可能会遇到一个问题,即我们需要根据特定的键对字典进行分组,并在对相似键的值进行分组的同时对某些键进行求和。这是一个特殊的问题,但可以在 Web 开发等领域有应用。让我们讨论一下可以执行此任务的某种方式。
Input : test_list = [{‘geeks’: 10, ‘best’: 8, ‘Gfg’: 6}, {‘geeks’: 12, ‘best’: 11, ‘Gfg’: 4}]
Output : {4: {‘geeks’: 12, ‘best’: 11}, 6: {‘geeks’: 10, ‘best’: 8}}
Input : test_list = [{‘CS’: 14, ‘best’: 9, ‘geeks’: 7, ‘Gfg’: 14}]
Output : {14: {‘best’: 9, ‘geeks’: 7}}
方法#1:使用循环
这是可以执行此任务的蛮力方式。在此我们手动遍历字典中的每个键,并根据键执行所需的分组,并构造所需的分组和求和字典。
# Python3 code to demonstrate working of
# Summation Grouping in Dictionary List
# Using loop
# initializing list
test_list = [{'Gfg' : 1, 'id' : 2, 'best' : 8, 'geeks' : 10},
{'Gfg' : 4, 'id' : 4, 'best': 10, 'geeks' : 12},
{'Gfg' : 4, 'id' : 8, 'best': 11, 'geeks' : 15}]
# printing original list
print("The original list is : " + str(test_list))
# initializing group key
grp_key = 'Gfg'
# initializing sum keys
sum_keys = ['best', 'geeks']
# Summation Grouping in Dictionary List
# Using loop
res = {}
for sub in test_list:
ele = sub[grp_key]
if ele not in res:
res[ele] = {x: 0 for x in sum_keys}
for y in sum_keys:
res[ele][y] += int(sub[y])
# printing result
print("The grouped list : " + str(res))
The original list is : [{‘geeks’: 10, ‘id’: 2, ‘best’: 8, ‘Gfg’: 1}, {‘geeks’: 12, ‘id’: 4, ‘best’: 10, ‘Gfg’: 4}, {‘geeks’: 15, ‘id’: 8, ‘best’: 11, ‘Gfg’: 4}]
The grouped list : {1: {‘geeks’: 10, ‘best’: 8}, 4: {‘geeks’: 27, ‘best’: 21}}