📜  Python|等键列表求和

📅  最后修改于: 2022-05-13 01:54:40.522000             🧑  作者: Mango

Python|等键列表求和

有时,在使用字典时,我们可能会遇到一个问题,即我们有很多字典,我们需要像键一样求和。这个问题看起来很常见,但复杂的是如果键的值是列表,我们需要将元素添加到类似键的列表中。让我们讨论一下解决这个问题的方法。

方法:使用列表理解 + items() + sum()
这个问题可以使用列表理解和 sum() 来解决,sum() 可以用来对列表内容求和,也可以使用 items 方法来获取字典键和值。

# Python3 code to demonstrate working of
# Equal Keys List Summation
# Using items() + list comprehension + sum()
  
# initializing dictionaries
test_dict1 = {'Gfg' : [1, 2, 3], 'for' : [2, 4], 'CS' : [7, 8]}
test_dict2 = {'Gfg' : [10, 11], 'for' : [5], 'CS' : [0, 18]}
  
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
  
# Using items() + list comprehension + sum()
# Equal Keys List Summation
res = {key: sum(value) + sum(test_dict2[key]) for key, value in test_dict1.items()}
  
# printing result 
print("The summation of dictionary values is : " + str(res))
输出 :
The original dictionary 1 is : {'CS': [7, 8], 'for': [2, 4], 'Gfg': [1, 2, 3]}
The original dictionary 2 is : {'CS': [0, 18], 'for': [5], 'Gfg': [10, 11]}
The summation of dictionary values is : {'CS': 33, 'for': 11, 'Gfg': 27}