Python – Test if Values Sum is Greater than Keys Sum in dictionary

• Last Updated : 12 Nov, 2020

Given a Dictionary, check if the summation of values is greater than Keys sum.

Input : test_dict = {5:3, 1:3, 10:4, 7:3, 8:1, 9:5}
Output : False
Explanation : Values sum = 19 < 40, which is key sum, i.e false.

Input : test_dict = {5:3, 1:4}
Output : True
Explanation : Values sum = 7 > 6, which is key sum, i.e true.

Method #1: Using loop

In this, we compute keys and values sum in separate counter, and after the loop equate the values, if values are greater than Keys summation, True is returned.

Python3

 # Python3 code to demonstrate working of# Test if Values Sum is Greater than Keys Sum in dictionary# Using loop  # initializing dictionarytest_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  key_sum = 0val_sum = 0  for key in test_dict:      # getting sum    key_sum += key    val_sum += test_dict[key]  # checking if val_sum greater than key sumres = val_sum > key_sum  # printing resultprint("The required result : " + str(res))
Output
The original dictionary is : {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
The required result : False

Method #2 : Using sum() + values()  + keys()

In this way, keys sum and values sum is extracted using keys(), values() and summation using sum(), the required condition is checked and verdict is computed.

Python3

 # Python3 code to demonstrate working of# Test if Values Sum is Greater than Keys Sum in dictionary# Using sum() + values()  + keys()  # initializing dictionarytest_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  res = sum(list(test_dict.keys())) < sum(list(test_dict.values()))  # printing resultprint("The required result : " + str(res))
Output
The original dictionary is : {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
The required result : False

My Personal Notes arrow_drop_up