Open In App

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

Given a Dictionary, check if the summation of values is greater than the 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 equates the values, if values are greater than the Keys summation, True is returned.




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

Time complexity: O(n), where n is the number of values in the dictionary.
Auxiliary Space: O(1), constant extra space is required

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 code to demonstrate working of
# Test if Values Sum is Greater than Keys Sum in dictionary
# Using sum() + values()  + keys()
 
# initializing dictionary
test_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
res = sum(list(test_dict.keys())) < sum(list(test_dict.values()))
 
# printing result
print("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#3: Using dictionary comprehension




# initializing dictionary
test_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# finding the sum of keys and values using dictionary comprehension
key_sum = sum([key for key in test_dict.keys()])
val_sum = sum([val for val in test_dict.values()])
 
# checking if val_sum greater than key sum
res = val_sum > key_sum
 
# printing result
print("The required result : " + str(res))
#This code is contributed by Vinay Pinjala.

Output
The original dictionary is : {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
The required result : False

Time complexity: O(n)
Auxiliary Space: O(n)

Method 4: Using the built-in function reduce() from the functools module to sum the keys and values of the dictionary.

Here are the steps to implement this approach:

  1. Import the reduce() function from the functools module.
  2. Define a lambda function to add two values together.
  3. Use reduce() to sum the keys and values of the dictionary separately.
  4. Compare the sum of values with the sum of keys to check if the former is greater than the latter.




from functools import reduce
 
# Initializing dictionary
test_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
 
# Printing original dictionary
print("The original dictionary is: " + str(test_dict))
 
# Summing the keys and values
# using reduce() function
key_sum = reduce(lambda x, y: x + y, test_dict.keys())
val_sum = reduce(lambda x, y: x + y, test_dict.values())
 
# Comparing the sums to check the result
res = val_sum > key_sum
 
# Printing the result
print("The required result is: " + str(res))

Output
The original dictionary is: {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
The required result is: False

Time complexity: O(n)
Auxiliary space: O(1)

Method 5: Using numpy

  1. Initialize the dictionary test_dict with key-value pairs.
  2. Print the original dictionary.
  3. Convert the keys and values of the dictionary into numpy arrays using list() and np.array() functions.
  4. Find the sum of keys and values using np.sum() function.
  5. Check if the val_sum is greater than key_sum using “>” operator.
  6. Store the result of the comparison in the variable res.
  7. Print the result.




import numpy as np
 
# Initializing dictionary
test_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
 
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Creating numpy arrays from dictionary keys and values
keys_arr = np.array(list(test_dict.keys()))
vals_arr = np.array(list(test_dict.values()))
 
# Finding the sum of keys and values using numpy
key_sum = np.sum(keys_arr)
val_sum = np.sum(vals_arr)
 
# Checking if val_sum greater than key sum
res = val_sum > key_sum
 
# Pinting result
print("The required result : " + str(res))
 
# This code is contributed by Rayudu

Output
The original dictionary is: {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
The required result is: False

Time complexity: O(n), where n is the size of the dictionary because creating the numpy arrays and performing the sum operation takes linear time in the size of the dictionary.

Auxiliary Space: O(n), because the numpy arrays created from the keys and values of the dictionary use extra memory proportional to the size of the dictionary. However, the space used by the original dictionary is not included in this analysis because it is already allocated before the numpy arrays are created.

Method#6: Using Recursive method

Steps:

  1. Define a function called is_val_sum_greater_than_key_sum that takes a dictionary (d) and two optional integer arguments for the running sums of keys (key_sum) and values (val_sum).
  2. Check if the dictionary is empty. If it is, return True if the sum of values is greater than the sum of keys, and False otherwise.
  3. If the dictionary is not empty, pop an item from the dictionary using the popitem() method. This returns a tuple of the key and value of the last item in the dictionary.
  4. Add the key and value to the running sums of keys and values, respectively.
  5. Make a recursive call to the same function with the updated dictionary and running sums.
  6. When the recursive call returns, the function will have computed the sums of all the items in the dictionary.
  7. Compare the sum of values to the sum of keys, and return True if the former is greater than the latter, and False otherwise.




def is_val_sum_greater_than_key_sum(d, key_sum=0, val_sum=0):
 
  if not d:
        return val_sum > key_sum
    else:
        key, value = d.popitem()
        return is_val_sum_greater_than_key_sum(d, key_sum + key, val_sum + value)
 
 
# Initializing dictionmary 
test_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
 
print("The original dictionary is : " + str(test_dict))
 
# Calling above function
res = is_val_sum_greater_than_key_sum(test_dict)
 
# Printing result
print("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

Time complexity: O(n), where n is the number of items in the dictionary. This is because the function needs to visit each item in the dictionary exactly once, and the popitem() method takes constant time.

Auxiliary Space: O(n), because each recursive call creates a new stack frame and a new set of local variables for key_sum and val_sum. However, as soon as a recursive call returns, its stack frame is discarded and its local variables are no longer used, so the space usage is bounded by the depth of the recursion, which is also O(n) in the worst case.

Method #7: Using the built-in function map() and sum()

Approach:

  1. Initialize the dictionary.
  2. Compute the sum of keys using the built-in sum() function and map() function.
  3. Compute the sum of values using the built-in sum() function.
  4. Check if the value sum is greater than the key sum.
  5. Print the result.




# Python3 code to demonstrate working of
# Test if Values Sum is Greater than Keys Sum in dictionary
# using map() and sum()
 
# Initializing dictionary
test_dict = {5: 3, 1: 3, 10: 4, 7: 3, 8: 1, 9: 5}
 
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Computing sum of keys using map() and sum()
key_sum = sum(map(int, test_dict.keys()))
 
# Computing sum of values using sum()
val_sum = sum(test_dict.values())
 
# Checking if val_sum greater than key sum
res = val_sum > key_sum
 
# Printing the result
print("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

Time Complexity: O(N), where n is the number of key-value pairs in the dictionary.
Auxiliary Space: O(1), as we are not using any additional data structure.


Article Tags :