Table of contents

  1. Python | Aggregate values by tuple keys
  2. Python | Get all tuple keys from dictionary
  3. Python | Nth tuple index Subtraction by K
  4. Python | Unpacking dictionary keys into tuple
  5. Python | Zip Uneven Tuple

Python | Aggregate values by tuple keys

Aggregating values by tuple keys is a common operation in Python. This is usually done using dictionaries where tuple keys map to aggregated values. Here's a step-by-step tutorial on how to aggregate values based on tuple keys:

Objective: Given a list of data with tuple keys, we want to aggregate (sum) the values associated with identical tuple keys.

  • Sample Data: Let's consider a simple example where we have a list of data entries. Each entry is a tuple, where the first part of the tuple is a tuple key, and the second part is a value.
data = [
    (("apple", "red"), 5),
    (("banana", "yellow"), 3),
    (("apple", "red"), 7),
    (("banana", "yellow"), 6),
    (("grape", "purple"), 4)
  • Aggregation: We can aggregate the values for the same tuple keys using a dictionary.
aggregated = {}

for key, value in data:
    if key in aggregated:
        aggregated[key] += value
        aggregated[key] = value



{('apple', 'red'): 12, ('banana', 'yellow'): 9, ('grape', 'purple'): 4}
  • Using collections.defaultdict: The above approach can be simplified using collections.defaultdict.
from collections import defaultdict

aggregated_dd = defaultdict(int)

for key, value in data:
    aggregated_dd[key] += value


The output will be the same.

  • Fetching and Displaying the Aggregated Values: Once you have aggregated the data, you can fetch the tuple keys and associated aggregated values for display or further processing:
for key, value in aggregated.items():
    fruit, color = key
    print(f"The total for {color} {fruit} is: {value}")


The total for red apple is: 12
The total for yellow banana is: 9
The total for purple grape is: 4

This method can be expanded and adapted for various other aggregation functions or more complex tuple keys. The key takeaway is to understand how to leverage Python dictionaries for such tasks and how to use tuple keys effectively.

Python | Get all tuple keys from dictionary

To retrieve all the tuple keys from a dictionary in Python, you can use a list comprehension to filter out only those keys that are of type tuple. Here's how you can do this:

Given a dictionary:

dict_example = {
    (1, 2): 'a',
    (3, 4): 'b',
    'string_key': 'c',
    (5, 6, 7): 'd',
    'another_string_key': 'e'

To get all tuple keys:

tuple_keys = [key for key in dict_example.keys() if isinstance(key, tuple)]


[(1, 2), (3, 4), (5, 6, 7)]

As shown in the output, only the keys that are tuples are retrieved from the dictionary.

Python | Nth tuple index Subtraction by K

In this tutorial, we will learn how to subtract a given number K from the Nth index of each tuple in a list of tuples.

Problem Statement:

Given a list of tuples and a number K, subtract K from the element at the Nth index of each tuple.


  1. Input Validation:

    • Ensure that the list is not empty.
    • Ensure that N is within the range of tuple indices.
    • Ensure K is a valid number.
  2. Subtraction from Nth index:

    • Use a list comprehension to iterate through the list of tuples.
    • For each tuple, subtract K from the element at the Nth index and create a new tuple.
  3. Return the Modified List:

    • Return the modified list of tuples.

Python Implementation:

def subtract_k_from_nth_index(tuples_list, N, K):
    Subtract K from the Nth index of each tuple in tuples_list.
    # Input validation
    if not tuples_list or N < 0 or N >= len(tuples_list[0]) or not isinstance(K, (int, float)):
        raise ValueError("Invalid input.")
    # Subtract K from Nth index of each tuple
    modified_tuples = [tuple(val - K if idx == N else val for idx, val in enumerate(tup)) for tup in tuples_list]
    return modified_tuples

# Example
tuples_list = [(10, 20, 30), (40, 50, 60), (70, 80, 90)]
N = 1
K = 5

result = subtract_k_from_nth_index(tuples_list, N, K)
print(result)  # Outputs: [(10, 15, 30), (40, 45, 60), (70, 75, 90)]


In the provided example:

  • We have a list of tuples with values ranging from 10 to 90.
  • We want to subtract 5 from the 2nd element (i.e., index 1) of each tuple.
  • The result is a modified list of tuples: [(10, 15, 30), (40, 45, 60), (70, 75, 90)].


Subtracting a value K from the Nth index of each tuple in a list of tuples can be efficiently accomplished using Python's list comprehensions. The approach provided here allows for a concise and readable way to achieve the desired outcome. Ensure to perform input validation for robustness.

Python | Unpacking dictionary keys into tuple

In Python, if you have a dictionary and you want to unpack its keys into a tuple, you can easily do that by converting the dictionary keys view to a tuple.

Here's an example:

# Sample dictionary
data = {
    'a': 1,
    'b': 2,
    'c': 3,
    'd': 4

# Unpack dictionary keys into a tuple
keys_tuple = tuple(data.keys())

print(keys_tuple)  # Output: ('a', 'b', 'c', 'd')

In the code above, data.keys() returns a view of the dictionary's keys. By passing it to the tuple constructor, you can convert this view into a tuple containing all the dictionary's keys.

Python | Zip Uneven Tuple

When zipping uneven tuples in Python, you'll generally face the same issues as zipping uneven lists. By default, the zip function will stop when the smallest tuple is exhausted, ignoring the remaining elements in the longer tuple(s).

However, you might want to zip tuples of unequal lengths by either padding the shorter tuple(s) with a default value or by using other techniques. In this tutorial, we will explore these approaches.


Two tuples of different lengths:

tuple1 = (1, 2, 3, 4)
tuple2 = ('a', 'b', 'c')


Zip these tuples together.

1. Using Built-in zip:

Using zip directly will result in pairs only till the smallest tuple is exhausted.

zipped = tuple(zip(tuple1, tuple2))
print(zipped)  # Output: ((1, 'a'), (2, 'b'), (3, 'c'))

2. Using itertools.zip_longest:

The zip_longest function from the itertools module allows zipping of tuples of unequal lengths by filling in the gaps with a specified value.

import itertools

zipped = tuple(itertools.zip_longest(tuple1, tuple2, fillvalue=None))
print(zipped)  # Output: ((1, 'a'), (2, 'b'), (3, 'c'), (4, None))

Customizing Fill Value:

You can customize the fillvalue:

zipped = tuple(itertools.zip_longest(tuple1, tuple2, fillvalue='z'))
print(zipped)  # Output: ((1, 'a'), (2, 'b'), (3, 'c'), (4, 'z'))

3. Using Loops:

You can also manually loop through the tuples to achieve the desired behavior:

max_len = max(len(tuple1), len(tuple2))
result = []

for i in range(max_len):
    val1 = tuple1[i] if i < len(tuple1) else None
    val2 = tuple2[i] if i < len(tuple2) else None
    result.append((val1, val2))

zipped = tuple(result)
print(zipped)  # Output: ((1, 'a'), (2, 'b'), (3, 'c'), (4, None))


Zipping uneven tuples in Python can be accomplished using the built-in zip function if you're okay with truncating based on the shortest tuple. If you want to handle uneven lengths with default values, then itertools.zip_longest is your best choice. For more nuanced or complex scenarios, manually iterating through the tuples might be required.

More Python Questions

More C# Questions