Python - Custom Tuple Key Summation in Dictionary
Last Updated :
22 Apr, 2023
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform group summation of values, of certain key on particular index of tuple keys of dictionary. This problem is quite custom, but can have application in domains that revolves around data processing. Let's discuss certain ways in which this task can be performed.
Input : test_dict = {('a', 'b'): 14, ('c', 'a'): 16, ('a', 'c'): 67} K = 'c', idx = 1
Output : 16
Input : test_dict = {('a', 'b'): 14, ('c', 'a'): 16, ('a', 'c'): 67} K = 'c', idx = 2
Output : 67
Method #1: Using sum() + generator expression The combination of above functions can be used to solve this problem. In this, we perform summation using sum() and perform task of filtering using generator expression.
Python3
# Python3 code to demonstrate working of
# Custom Tuple Key Summation in Dictionary
# Using sum() + generator expression
# initializing dictionary
test_dict = {('a', 'b'): 14, ('c', 'a'): 16, ('a', 'c'): 67, ('b', 'a'): 17}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 'a'
# initializing index
idx = 1
# Custom Tuple Key Summation in Dictionary
# Using sum() + generator expression
res = sum(val for key, val in test_dict.items() if key[idx - 1] == K)
# printing result
print("The grouped summation : " + str(res))
Output : The original dictionary is : {('a', 'b'): 14, ('c', 'a'): 16, ('a', 'c'): 67, ('b', 'a'): 17}
The grouped summation : 81
Time complexity: O(n), where n is the number of items in the dictionary.
Auxiliary space: O(1), since only a few variables are being used to store values and no additional data structure is being created.
Method #2: Using sum() + map() + lambda The combination of above functions can be used to solve this problem. In this, we perform the task of perform summation using sum() and map() + lambda is used to perform task of checking conditions.
Python3
# Python3 code to demonstrate working of
# Custom Tuple Key Summation in Dictionary
# Using sum() + map() + lambda
# initializing dictionary
test_dict = {('a', 'b'): 14, ('c', 'a'): 16, ('a', 'c'): 67, ('b', 'a'): 17}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 'a'
# initializing index
idx = 1
# Custom Tuple Key Summation in Dictionary
# Using sum() + map() + lambda
res = sum(map(lambda sub: sub[1], filter(lambda ele: ele[0][idx - 1] == K,
test_dict.items())))
# printing result
print("The grouped summation : " + str(res))
Output : The original dictionary is : {('a', 'b'): 14, ('c', 'a'): 16, ('a', 'c'): 67, ('b', 'a'): 17}
The grouped summation : 81
Time complexity: O(n), where n is the number of elements in the dictionary.
Auxiliary space: O(1), as the memory usage of the program is constant and does not depend on the size of the input.
Method #3: Using a for loop
- Initialize a dictionary called test_dict with some key-value pairs.
- Define the variables K and idx to specify which key to group by.
- Initialize a variable called res to 0 to hold the final result.
- Iterate over the key-value pairs in the dictionary using a for loop.
- Check if the idx-th element of the current key is equal to K.
- If the condition is true, add the value to the res variable.
- After the loop finishes, print the final result.
Python3
# Python3 code to demonstrate working of
# Custom Tuple Key Summation in Dictionary
# Using a for loop
# initializing dictionary
test_dict = {('a', 'b'): 14, ('c', 'a'): 16, ('a', 'c'): 67, ('b', 'a'): 17}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 'a'
# initializing index
idx = 1
# Custom Tuple Key Summation in Dictionary
res = 0
for key, val in test_dict.items():
if key[idx - 1] == K:
res += val
# printing result
print("The grouped summation : " + str(res))
OutputThe original dictionary is : {('a', 'b'): 14, ('c', 'a'): 16, ('a', 'c'): 67, ('b', 'a'): 17}
The grouped summation : 81
Time Complexity: O(n)
- In the worst case, the for loop iterates over all n items in the dictionary, so the time complexity is O(n).
Auxiliary Space: O(1)
- The space used by the program is constant and does not depend on the size of the input dictionary, so the space complexity is O(1).
Method #4: Using Dictionary Comprehension
Using dictionary comprehension, the sum function is used to iterate through the key-value pairs of the dictionary and add the values that satisfy the specified condition. The final sum is stored in the variable res, which is printed as the output.
Python3
# Python3 code to demonstrate working of
# Custom Tuple Key Summation in Dictionary
# Using Dictionary Comprehension
# initializing dictionary
test_dict = {('a', 'b'): 14, ('c', 'a'): 16, ('a', 'c'): 67, ('b', 'a'): 17}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 'a'
# initializing index
idx = 1
# Custom Tuple Key Summation in Dictionary
res = sum(val for key, val in test_dict.items() if key[idx - 1] == K)
# printing result
print("The grouped summation : " + str(res))
OutputThe original dictionary is : {('a', 'b'): 14, ('c', 'a'): 16, ('a', 'c'): 67, ('b', 'a'): 17}
The grouped summation : 81
Time complexity: O(N), where N is the number of key-value pairs in the dictionary. This is because the program iterates through each key-value pair exactly once and performs constant-time operations on each.
Auxiliary space: O(1)
Method #5: Using filter() + reduce() function
We can use the filter() function to filter out the dictionary keys that have 'K' at the desired index. Then, we can use the reduce() function to calculate the sum of the values of the remaining keys.
step by step approach:
Define a lambda function to filter out the keys that have 'K' at the desired index. The lambda function will take a key as input and return True if the key[idx - 1] == K, else False.
Use the filter() function to filter out the keys that pass the filter condition defined in step 1.
Use the reduce() function from the functools module to calculate the sum of the values of the filtered keys.
Store the result in a variable called res.
Print the result.
Python3
import functools
# initializing dictionary
test_dict = {('a', 'b'): 14, ('c', 'a'): 16, ('a', 'c'): 67, ('b', 'a'): 17}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 'a'
# initializing index
idx = 1
# Custom Tuple Key Summation in Dictionary using filter() and reduce()
res = functools.reduce(lambda a, b: a + b[1], filter(lambda x: x[0][idx - 1] == K, test_dict.items()), 0)
# printing result
print("The grouped summation : " + str(res))
OutputThe original dictionary is : {('a', 'b'): 14, ('c', 'a'): 16, ('a', 'c'): 67, ('b', 'a'): 17}
The grouped summation : 81
Time complexity: O(n), where n is the number of items in the dictionary.
Auxiliary space: O(1) - The filter and reduce functions are being applied on the fly, without creating any additional data structures.
Method #6: Using a list comprehension
steps :
Initialize a variable total to 0.
Use a list comprehension to loop through each key-value pair in the dictionary, checking if the key contains the character K at index idx - 1.
If the key matches the condition, add the value to total.
Return total.
Python3
test_dict = {('a', 'b'): 14, ('c', 'a'): 16, ('a', 'c'): 67, ('b', 'a'): 17}
K = 'a'
idx = 1
total = sum(val for key, val in test_dict.items() if key[idx - 1] == K)
print("The grouped summation : " + str(total))
OutputThe grouped summation : 81
Time complexity: O(n)
Auxiliary space: O(1)
Similar Reads
Python - Summation of Custom nested keys in Dictionary
Given a dictionary with keys as nested dictionaries, find the sum of values of certain custom keys inside the nested dictionary. Input : test_dict = {'Gfg' : {1 : 6, 5: 9, 9: 12}, 'is' : {1 : 9, 5: 7, 9: 2}, 'best' : {1 : 3, 5: 4, 9: 14}}, sum_key = [1] Output : 18 Explanation : 6 + 9 + 3 = 18, only
10 min read
Python | Value summation of key in dictionary
Many operations such as grouping and conversions are possible using Python dictionaries. But sometimes, we can also have a problem in which we need to perform the aggregation of values of key in dictionary list. This task is common in day-day programming. Let's discuss certain ways in which this tas
6 min read
Python - Tuple to Dictionary Summation conversion
Sometimes, while working with Python tuples, we can have a problem in which we can have data points in tuples, and we need to convert them to dictionary after performing summation of similar keys. This kind of operation can also be extended to max, min or product. This can occur in data domains. Let
5 min read
Python - Summation of tuple dictionary values
Sometimes, while working with data, we can have a problem in which we need to find the summation of tuple elements that are received as values of dictionary. We may have a problem to get index wise summation. Letâs discuss certain ways in which this particular problem can be solved. Method #1: Using
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 - Nested Dictionary values summation
Sometimes, while working with Python dictionaries, we can have problem in which we have nested records and we need cumulative summation of it's keys values. This can have possible application in domains such as web development and competitive programming. Lets discuss certain ways in which this task
8 min read
Convert Nested Tuple to Custom Key Dictionary - Python
The task is to convert a nested tuple into a dictionary with custom keys. Each tuple in the nested structure contains multiple elements, and the goal is to map these elements to specific keys in a dictionary.For example, given the tuple a = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10)), the goal i
3 min read
Python | Summation of dictionary list values
Sometimes, while working with Python dictionaries, we can have its values as lists. In this can, we can have a problem in that we just require the count of elements in those lists as a whole. This can be a problem in Data Science in which we need to get total records in observations. Let's discuss c
6 min read
Python - Dictionary Values Mapped Summation
Given a dictionary with a values list, our task is to extract the sum of values, found using mappings. Input : test_dict = {4 : ['a', 'v', 'b', 'e'], 1 : ['g', 'f', 'g'], 3 : ['e', 'v']}, map_vals = {'a' : 3, 'g' : 8, 'f' : 10, 'b' : 4, 'e' : 7, 'v' : 2} Output : {4: 16, 1: 26, 3: 9} Explanation : "
6 min read
Python | Tuple key dictionary conversion
Interconversions are always required while coding in Python, also because of expansion of Python as a prime language in the field of Data Science. This article discusses yet another problem that converts to dictionary and assigns keys as first pair elements as tuple and rest as itâs value. Letâs dis
5 min read