Monday, November 18, 2024
Google search engine
HomeLanguagesPython – Selective Key Values Summation

Python – Selective Key Values Summation

Sometimes, while working with Python dictionaries, we can have a problem in which we desire to get summation of certain keys’ values in dictionary. This kind of application can have usecase in many domains such as day-day programming. Let’s discuss certain ways in which this task can be performed.

Input : test_dict = {‘Gfg’ : 4, ‘is’ : 2, ‘best’ : 7}, key_list = [‘Gfg’, ‘best’] Output : 11 Input : test_dict = {‘Gfg’ : 4, ‘best’ : 7}, key_list = [‘Gfg’] Output : 4

Method #1 : Using loop This is one of the ways in which this task can be performed. In this, we iterate for target list keys and sum the corresponding values from dictionary. 

Python3




# Python3 code to demonstrate working of
# Selective Key Values Summation
# Using loop
 
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 7, 'for' : 9, 'neveropen' : 10}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing keys_list
key_list = ['Gfg', 'best', 'neveropen']
 
# Selective Key Values Summation
# Using loop
res = 0
for key in key_list:
    res += test_dict[key]
         
# printing result
print("The keys summation : " + str(res))
# Python3 code to demonstrate working of
# Selective Key Values Summation
# Using loop
 
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 7, 'for' : 9, 'neveropen' : 10}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing keys_list
key_list = ['Gfg', 'best', 'neveropen']
 
# Selective Key Values Summation
# Using loop
res = 0
for key in key_list:
    res += test_dict[key]
         
# printing result
print("The keys summation : " + str(res))


Output : 

The original dictionary is : {'Gfg': 4, 'is': 2, 'best': 7, 'for': 9, 'neveropen': 10}
The keys summation : 21

Time complexity: O(n), where n is the number of keys in the key_list. 

Auxiliary space: O(1),, where n is the number of keys in the key_list. 

Method #2: Using sum() + list comprehension

The combination of above functions can be used to solve this problem. In this, we perform summation using sum() and list comprehension is used to perform task of iteration. 

Python3




# Python3 code to demonstrate working of
# Selective Key Values Summation
# Using sum() + list comprehension
 
# initializing dictionary
test_dict = {'Gfg': 4, 'is': 2, 'best': 7, 'for': 9, 'neveropen': 10}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing keys_list
key_list = ['Gfg', 'best', 'neveropen']
 
# Selective Key Values Summation
# Using sum() + list comprehension
res = sum([test_dict[key] for key in key_list])
 
# printing result
print("The keys summation : " + str(res))


Output : 

The original dictionary is : {'Gfg': 4, 'is': 2, 'best': 7, 'for': 9, 'neveropen': 10}
The keys summation : 21

Method #3 : Using items()

The given code takes a dictionary and a list of keys as input and selectively sums up the values corresponding to the keys present in the list. It iterates through the key-value pairs of the dictionary and adds the value to a sum variable if the key is present in the key list. Finally, it returns the sum.

Algorithm

1. Initialize a variable sum to 0
2. Iterate over the key-value pairs in the dictionary
3. If the current key is present in the key list, add its value to the sum
4. Return the sum

Python3




def selective_sum(test_dict, key_list):
    # Initialize the sum to zero
    sum = 0
 
    # Iterate over the key-value pairs in the dictionary
    for key, value in test_dict.items():
 
        # If the current key is present in the key list, add its value to the sum
        if key in key_list:
            sum += value
 
    # Return the sum
    return sum
 
 
# Example usage
test_dict = {'Gfg': 4, 'is': 2, 'best': 7}
key_list = ['Gfg', 'best']
 
# Get the selective sum of values corresponding to the keys in the key list
result = selective_sum(test_dict, key_list)
 
# Print the result
print(result)


Output

11

Time complexity: O(n), where n is the number of key-value pairs in the dictionary. This is because the code iterates over each key-value pair in the dictionary once, and the time taken to perform each iteration is constant.
Auxiliary Space: O(1), because it uses a constant amount of extra space (the sum variable) regardless of the size of the input. The space used by the input dictionary and key list is not counted as part of the space complexity of the function, because they are part of the function’s input.

Method #4 :Using the built-in reduce() function from the functools module:

Algorithm:

  1. Initialize the dictionary test_dict with key-value pairs.
  2. Initialize the list key_list with keys that need to be summed.\
  3. Use a list comprehension to create a list of values from test_dict for keys in key_list.
  4. Use reduce() to sum the values in the list from the previous step.
  5. Print the sum as the keys summation.

Python3




from functools import reduce
 
# initializing dictionary
test_dict = {'Gfg': 4, 'is': 2, 'best': 7, 'for': 9, 'neveropen': 10}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
 
# initializing keys_list
key_list = ['Gfg', 'best', 'neveropen']
 
# Selective Key Values Summation using reduce()
res = reduce(lambda x, y: x + y, [test_dict[key] for key in key_list])
 
# printing result
print("The keys summation : " + str(res))
# This code is contributed by Jyothi pinjala


Output

The original dictionary is : {'Gfg': 4, 'is': 2, 'best': 7, 'for': 9, 'neveropen': 10}
The keys summation : 21

Time complexity : O(n), where n is the number of keys in the dictionary, as we are iterating over the key list and accessing the corresponding values in the dictionary.
Auxiliary space: O(k), where k is the number of keys in the key list, as we are creating a new list to hold the values corresponding to the given keys.

Method #6: Using map() and filter()

Use map() function to retrieve the values of the keys in the key_list and filter() function to remove the None values, which occur when a key is not present in the dictionary. Finally, you can use sum() function to add up the values.

Python3




test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 7, 'for' : 9, 'neveropen' : 10}
key_list = ['Gfg', 'best', 'neveropen']
 
res = sum(filter(None, map(test_dict.get, key_list)))
 
print("The keys summation : " + str(res))


Output

The keys summation : 21

Time complexity; O(k), where k is the number of keys in the key_list. 
Auxiliary space: O(k), where k is the number of keys in the key_list.

Method #6: Using dictionary comprehension

Approach:

  1. Initialize the test_dict with some key-value pairs.
  2. Initialize the key_list with a list of keys whose values we want to sum.
  3. Create a set of the keys in the test_dict using the keys() method and convert it to a set.
  4. Create a set of the keys in the key_list and convert it to a set.
  5. Find the intersection of the two sets using the intersection() method.
  6. Initialize the res variable to 0.
  7. Iterate over the keys in the common_keys set.
  8. For each key in common_keys, add its value to the res variable.
  9. Print the summation of the values corresponding to the keys in the common_keys set.

Python3




test_dict = {'Gfg': 4, 'is': 2, 'best': 7, 'for': 9, 'neveropen': 10}
key_list = ['Gfg', 'best', 'neveropen']
 
res = sum(test_dict[key] for key in test_dict if key in key_list)
 
print("The keys summation: ", res)


Output

The keys summation:  21

Time complexity: O(N) where N is the number of items in the dictionary, since we are iterating through the dictionary once.

Auxiliary space: O(1), since we only need to store a few variables (the dictionary, the list of keys, and the summation variable).

Method#7: Using Recursive method.

Algorithm: 

  1. Define a function selective_sum that takes in two arguments: test_dict and key_list.
  2. Check if the key_list is empty.
  3. If the key_list is empty, return 0.
  4. Otherwise, return the sum of the value associated with the first key in key_list and the result of calling selective_sum recursively with the remaining keys in key_list.

Python3




def selective_sum(test_dict, key_list):
    if not key_list:
        return 0
    else:
        return test_dict[key_list[0]] + selective_sum(test_dict, key_list[1:])
 
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 7, 'for' : 9, 'neveropen' : 10}
key_list = ['Gfg', 'best', 'neveropen']
 
print("The original dictionary is : " + str(test_dict))
res = selective_sum(test_dict, key_list)
print("The keys summation : " + str(res))


Output

The original dictionary is : {'Gfg': 4, 'is': 2, 'best': 7, 'for': 9, 'neveropen': 10}
The keys summation : 21

Time complexity of this algorithm is O(k), where k is the number of keys in key_list. This is because we need to perform k recursive calls to calculate the sum of the values associated with all keys in key_list.
Auxiliary space of this algorithm is O(k), where k is the number of keys in key_list. This is because we need to store k recursive calls on the call stack.

Method 8 :  using the built-in sum() function and a generator expression

Approach:

  1. Initialize the dictionary test_dict.
  2. Initialize the list of keys key_list.
  3. Use a generator expression to select the values of the keys in key_list from test_dict.
  4. Use the built-in sum() function to sum the values selected in step 3.
  5. Print the result.

Python3




# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 7, 'for' : 9, 'neveropen' : 10}
 
# initializing keys_list
key_list = ['Gfg', 'best', 'neveropen']
 
# Selective Key Values Summation using sum() and generator expression
res = sum(test_dict[key] for key in key_list)
 
# printing result
print("The keys summation : " + str(res))


Output

The keys summation : 21

Time complexity: O(n), where n is the number of keys in key_list.
Auxiliary space: O(1).

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments