Python – Selective Key Values Summation
Last Updated :
08 May, 2023
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
test_dict = { 'Gfg' : 4 , 'is' : 2 , 'best' : 7 , 'for' : 9 , 'geeks' : 10 }
print ( "The original dictionary is : " + str (test_dict))
key_list = [ 'Gfg' , 'best' , 'geeks' ]
res = 0
for key in key_list:
res + = test_dict[key]
print ( "The keys summation : " + str (res))
test_dict = { 'Gfg' : 4 , 'is' : 2 , 'best' : 7 , 'for' : 9 , 'geeks' : 10 }
print ( "The original dictionary is : " + str (test_dict))
key_list = [ 'Gfg' , 'best' , 'geeks' ]
res = 0
for key in key_list:
res + = test_dict[key]
print ( "The keys summation : " + str (res))
|
Output :
The original dictionary is : {'Gfg': 4, 'is': 2, 'best': 7, 'for': 9, 'geeks': 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
test_dict = { 'Gfg' : 4 , 'is' : 2 , 'best' : 7 , 'for' : 9 , 'geeks' : 10 }
print ( "The original dictionary is : " + str (test_dict))
key_list = [ 'Gfg' , 'best' , 'geeks' ]
res = sum ([test_dict[key] for key in key_list])
print ( "The keys summation : " + str (res))
|
Output :
The original dictionary is : {'Gfg': 4, 'is': 2, 'best': 7, 'for': 9, 'geeks': 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):
sum = 0
for key, value in test_dict.items():
if key in key_list:
sum + = value
return sum
test_dict = { 'Gfg' : 4 , 'is' : 2 , 'best' : 7 }
key_list = [ 'Gfg' , 'best' ]
result = selective_sum(test_dict, key_list)
print (result)
|
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:
- Initialize the dictionary test_dict with key-value pairs.
- Initialize the list key_list with keys that need to be summed.\
- Use a list comprehension to create a list of values from test_dict for keys in key_list.
- Use reduce() to sum the values in the list from the previous step.
- Print the sum as the keys summation.
Python3
from functools import reduce
test_dict = { 'Gfg' : 4 , 'is' : 2 , 'best' : 7 , 'for' : 9 , 'geeks' : 10 }
print ( "The original dictionary is : " + str (test_dict))
key_list = [ 'Gfg' , 'best' , 'geeks' ]
res = reduce ( lambda x, y: x + y, [test_dict[key] for key in key_list])
print ( "The keys summation : " + str (res))
|
Output
The original dictionary is : {'Gfg': 4, 'is': 2, 'best': 7, 'for': 9, 'geeks': 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 , 'geeks' : 10 }
key_list = [ 'Gfg' , 'best' , 'geeks' ]
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:
- Initialize the test_dict with some key-value pairs.
- Initialize the key_list with a list of keys whose values we want to sum.
- Create a set of the keys in the test_dict using the keys() method and convert it to a set.
- Create a set of the keys in the key_list and convert it to a set.
- Find the intersection of the two sets using the intersection() method.
- Initialize the res variable to 0.
- Iterate over the keys in the common_keys set.
- For each key in common_keys, add its value to the res variable.
- 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 , 'geeks' : 10 }
key_list = [ 'Gfg' , 'best' , 'geeks' ]
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:
- Define a function selective_sum that takes in two arguments: test_dict and key_list.
- Check if the key_list is empty.
- If the key_list is empty, return 0.
- 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 , 'geeks' : 10 }
key_list = [ 'Gfg' , 'best' , 'geeks' ]
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, 'geeks': 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:
- Initialize the dictionary test_dict.
- Initialize the list of keys key_list.
- Use a generator expression to select the values of the keys in key_list from test_dict.
- Use the built-in sum() function to sum the values selected in step 3.
- Print the result.
Python3
test_dict = { 'Gfg' : 4 , 'is' : 2 , 'best' : 7 , 'for' : 9 , 'geeks' : 10 }
key_list = [ 'Gfg' , 'best' , 'geeks' ]
res = sum (test_dict[key] for key in key_list)
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).
Similar Reads
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 compreh
7 min read
Python | Selective Records Value Summation
Sometimes, while using a list of tuples, we come across a problem in which we have e certain list of keys and we just need the summation of values of those keys from the list of tuples. This has a utility in rating or summation of specific entities. Letâs discuss certain ways in which this can be do
11 min read
Python | Selective indices Summation
Accessing an element from its index is easier task in python, just using the [] operator in a list does the trick. But in certain situations we are presented with tasks when we have more than once indices and we need to get all the elements corresponding to those indices and then perform the summati
6 min read
Python - Nested record values summation
Sometimes, while working with records, we can have problems in which we need to perform summation of nested keys of a key and record the sum as key's value. This can have possible applications in domains such as Data Science and web development. Let us discuss certain ways in which this task can be
7 min read
Python | Segregating Key's Values
Many times when we have the requirement to separate the values of a dictionary key in case we have a list of dictionary and need to separate it's different key's values. This is quite useful utility used in web development. Let's discuss certain ways in which this can be done. Method #1: Using list
4 min read
Python - Sort Dictionary by Values Summation
Give a dictionary with value lists, sort the keys by summation of values in value list. Input : test_dict = {'Gfg' : [6, 7, 4], 'best' : [7, 6, 5]} Output : {'Gfg': 17, 'best': 18} Explanation : Sorted by sum, and replaced. Input : test_dict = {'Gfg' : [8], 'best' : [5]} Output : {'best': 5, 'Gfg':
4 min read
Python | Tail Sliced List Summation
We often come to the situations in which we need to decrease the size of the list by truncating the last elements of the list and perform remaining list summation. This particular problem occurs when we need to optimize memory. This has its application in the day-day programming when sometimes we re
4 min read
Python - Sort Dictionary by key-value Summation
Given a Dictionary, sort by summation of key and value. Input : test_dict = {3:5, 1:3, 4:6, 2:7, 8:1} Output : {1: 3, 3: 5, 2: 7, 8: 1, 4: 6} Explanation : 4 < 8 < 9 = 9 < 10 are increasing summation of keys and values. Input : test_dict = {3:5, 1:3, 4:6, 2:7} Output : {1: 3, 3: 5, 2: 7, 4:
5 min read
Python - Index Value Summation List
To access the elements of lists, there are various methods. But sometimes we may require to access the element along with the index on which it is found and compute its summation, and for that, we may need to employ different strategies. This article discusses some of those strategies. Method 1: Nai
4 min read
Python | Chuncked summation every K value
The prefix array is quite famous in the programming world. This article would discuss a variation of this scheme. To perform a chunked summation where the sum resets at every occurrence of the value K , we need to modify the summation logic. The idea is: Traverse the list.Keep adding to the cumulati
3 min read