 GeeksforGeeks App
Open App Browser
Continue

# Python – Custom Tuple Key Summation in Dictionary

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))`

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)

• 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))`

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 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))`

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) – 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.

## 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))`

Output

```The grouped summation : 81
```

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

My Personal Notes arrow_drop_up