Python - Convert Nested Tuple to Custom Key Dictionary

Python - Convert Nested Tuple to Custom Key Dictionary

In this tutorial, we will consider converting a nested tuple into a dictionary, where each nested tuple's first element is used as a key and the remaining elements are used as the value. This type of operation is common in data processing tasks.

Given:

A nested tuple:

nested_tuple = (('A', 1, 2, 3), ('B', 4, 5), ('C', 6, 7, 8, 9)) 

Desired Outcome:

Convert the nested tuple into a dictionary, such that the first element of each tuple becomes the key and the rest of the elements become the values in a list:

{ 'A': [1, 2, 3], 'B': [4, 5], 'C': [6, 7, 8, 9] } 

Tutorial:

1. Using Dictionary Comprehension:

Iterate over each tuple in the nested tuple, using the first element as the key and the rest as the values:

result_dict = {t[0]: list(t[1:]) for t in nested_tuple} 

2. Print the Result:

print(result_dict) 

Full Code:

nested_tuple = (('A', 1, 2, 3), ('B', 4, 5), ('C', 6, 7, 8, 9)) result_dict = {t[0]: list(t[1:]) for t in nested_tuple} print(result_dict) 

Output:

{ 'A': [1, 2, 3], 'B': [4, 5], 'C': [6, 7, 8, 9] } 

Notes:

  • The operation t[0]: list(t[1:]) breaks down as follows:
    • t[0]: This retrieves the first element from the tuple, which is used as the key.
    • list(t[1:]): This retrieves all elements from the tuple starting from the second element (t[1]) up to the last element. The result is a list that serves as the value.
  • This approach assumes that each nested tuple has at least one element. If there's a chance some tuples could be empty, you'd need to add a conditional check to avoid potential errors.
  • If there are more complexities in the tuple structure, additional logic might be required. The method presented here works for the provided nested tuple structure.

More Tags

x11 symfony2-easyadmin controlvalueaccessor sonarqube-scan dice dynamic-html pfx momentjs attr dialect

More Programming Guides

Other Guides

More Programming Examples