Python – Key Lists Summations

Sometimes, while working with Python Dictionaries, we can have problem in which we need to perform the replace of key with values with sum of all keys in values. This can have application in many domains that include data computations, such as Machine Learning. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using sum() + loop
This is one of the ways in which this task can be performed. In this, we perform the summation using sum, and iteration to each key is done in brute way using loop.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Key Values Summations
# Using sum() + loop
  
# initializing dictionary
test_dict = {'gfg' : [4, 6, 8], 'is' : [9, 8, 2], 'best' : [10, 3, 2]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Key Values Summations
# Using sum() + loop
for key, value in test_dict.items():
    test_dict[key] = sum(value)
      
# printing result 
print("The summation keys are : " + str(test_dict)) 

chevron_right


Output :

The original dictionary is : {‘gfg’: [4, 6, 8], ‘is’: [9, 8, 2], ‘best’: [10, 3, 2]}
The summation keys are : {‘gfg’: 18, ‘is’: 19, ‘best’: 15}

 



Method #2 : Using dictionary comprehension + sum()
This is yet another way in which this task can be performed. This is similar to above method, just a shorthand version.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Key Values Summations
# Using dictionary comprehension + sum()
  
# initializing dictionary
test_dict = {'gfg' : [4, 6, 8], 'is' : [9, 8, 2], 'best' : [10, 3, 2]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Key Values Summations
# Using dictionary comprehension + sum()
res = {key : sum(val) for key, val in test_dict.items()}
      
# printing result 
print("The summation keys are : " + str(res)) 

chevron_right


Output :

The original dictionary is : {‘gfg’: [4, 6, 8], ‘is’: [9, 8, 2], ‘best’: [10, 3, 2]}
The summation keys are : {‘gfg’: 18, ‘is’: 19, ‘best’: 15}




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.