Friday, December 27, 2024
Google search engine
HomeLanguagesPython | Selective Keys Summation

Python | Selective Keys Summation

Sometimes while working with Python dictionaries, we might have a problem in which we require to just sum the selective key values from the dictionary. This problem can occur in the web development domain. Let’s discuss certain ways in which this problem can be solved. 

Method #1 : Using list comprehension + get() + sum()

The combination of the above functions can be used to perform this particular task. In this, we access the values using the get method and traverse the dictionary using list comprehension. We perform summation using sum() function.

Python3




# Python3 code to demonstrate working of
# Selective Keys Summation
# using list comprehension + get() + sum()
 
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
 
# Printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Initialize key list
key_list = ['gfg', 'best', 'CS']
 
# Selective Keys Summation
# using list comprehension + get() + sum()
res = sum([test_dict.get(key) for key in key_list])
 
# Printing result
print("The summation of Selective keys : " + str(res))


Output : 

The original dictionary : {'CS': 5, 'best': 3, 'is': 2, 'gfg': 1, 'for': 4}
The summation of Selective keys : 9

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #2 : Using itemgetter() + sum() 

This single function can be used to perform this particular task. It is built in to perform this specific task. It takes chain of keys and returns the corresponding values as a tuple which can be type casted. We perform summation using sum() function. 

Python3




# Python3 code to demonstrate working of
# Selective Keys Summation
# using itemgetter() + sum()
from operator import itemgetter
 
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
 
# Printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Initialize key list
key_list = ['gfg', 'best', 'CS']
 
# Selective Keys Summation
# using itemgetter() + sum()
res = sum(list(itemgetter(*key_list)(test_dict)))
 
# Printing result
print("The summation of Selective keys : " + str(res))


Output : 

The original dictionary : {'CS': 5, 'best': 3, 'is': 2, 'gfg': 1, 'for': 4}
The summation of Selective keys : 9

Time complexity: O(n), where n is the number of keys in the dictionary.
Auxiliary space: O(1), as the space complexity is constant regardless of the size of the input.

Method #3: Using for loop

Python3




# Python3 code to demonstrate working of
# Selective Keys Summation
 
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Initialize key list
key_list = ['gfg', 'best', 'CS']
 
 
# Selective Keys Summation
res = 0
for i in key_list:
    res += test_dict[i]
# printing result
print("The summation of Selective keys : " + str(res))


Output

The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
The summation of Selective keys : 9

Time complexity: O(n), where n is the number of elements in the key list.
Auxiliary space: O(1) since it uses a constant amount of additional space to store the res variable.

Method #4 : Using map() + sum()

Python3




# Selective Keys Summation
# using map() + sum()
 
# Initializing dictionary and list 
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
key_list = ['gfg', 'best', 'CS']
 
res = sum(map(test_dict.get, key_list))
 
# Printing result
print("The summation of Selective keys :", res)
 
# This code is contributed by Edula Vinay Kumar Reddy


Output

The summation of Selective keys : 9

Time Complexity: O(n) where n is the number of keys in the key_list
Auxiliary Space: O(n) where n is the number of keys in the key_list

Method #5: Using dictionary comprehension

Steps:

  1. Initialize a dictionary test_dict with some key-value pairs.
  2. Initialize a list key_list containing the keys to be summed.
  3. Use dictionary comprehension to filter the test_dict dictionary by keys in key_list. The filtered dictionary is stored in the variable filtered_dict.
  4. Use the sum() function to sum the values of the filtered dictionary filtered_dict. The result is stored in the variable total.
  5. Print the result.

Python3




# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
 
# Initialize key list
key_list = ['gfg', 'best', 'CS']
 
# Filtering the dictionary by keys in key_list
# using dictionary comprehension
filtered_dict = {k: test_dict[k] for k in key_list if k in test_dict}
 
# Sum the values of the filtered dictionary
total = sum(filtered_dict.values())
 
# Printing result
print("The summation of Selective keys : " + str(total))


Output

The summation of Selective keys : 9

Time Complexity: O(N) because we iterate over the dictionary and the key list once.
Auxiliary Space: O(K) where k is the number of keys in the key_list. This is because we create a new dictionary filtered_dict with a maximum size of k and a new variable total.

Method #6: Using the Recursive method

This function takes in a dictionary d and a list of keys and returns the sum of the values corresponding to the keys in the keys list.

If the length of the keys list is 1, then we just return the value corresponding to that key in the dictionary. Otherwise, we add the value corresponding to the first key in the keys list to the result of calling the function recursively with the dictionary and the rest of the keys list (i.e., all the keys except the first one).

Python3




def selective_keys_summation(d, keys):
 
    if len(keys) == 1:
        return d[keys[0]]
    else:
        return d[keys[0]] + selective_keys_summation(d, keys[1:])
 
 
# Initializing lists
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
key_list = ['gfg', 'best', 'CS']
 
res = selective_keys_summation(test_dict, key_list)
 
# Printing result
print("The summation of Selective keys : " + str(res))


Output

The summation of Selective keys : 9

Time complexity: O(K), where k is the number of keys in the key_list. This is because we make k recursive calls, one for each key in the key_list. However, since each call is essentially constant time (O(1)) due to dictionary lookups being constant time, the total time complexity is O(k).
Auxiliary Space: O(K), where k is the number of keys in the key_list. This is because we create k new stack frames on the call stack, one for each recursive call. However, since the depth of the call stack is at most k, the total space complexity is also O(k).

Method #7 : Using reduce() function

Steps:

  1. Import the reduce() function from the functools module.
  2. Define a function get_sum that takes two arguments, acc, and key, and returns the sum of acc and the value of the key in test_dict.
  3. Initialize a variable initial_value to 0.
  4. Use the reduce() function to iterate over each key in the key_list and accumulate the sum of the corresponding values in test_dict using the get_sum function.
  5. Assign the result of the reduce() function to a variable res.

Python3




from functools import reduce
 
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
key_list = ['gfg', 'best', 'CS']
 
def get_sum(acc, key):
    return acc + test_dict.get(key, 0)
 
initial_value = 0
res = reduce(get_sum, key_list, initial_value)
 
print("The summation of Selective keys :", res)


Output

The summation of Selective keys : 9

Time complexity: O(N), where n is the length of the 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