Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert Nested Tuple to Custom Key Dictionary in Python
Converting a nested tuple to a custom key dictionary is useful when transforming structured data. We can use list comprehension to iterate through tuples and create dictionaries with custom keys.
Syntax
[{key1: item[0], key2: item[1], key3: item[2]} for item in nested_tuple]
Example
Here's how to convert a nested tuple containing employee data into dictionaries with custom keys ?
my_tuple = ((6, 'Will', 13), (2, 'Mark', 15), (9, 'Rob', 12))
print("The tuple is:")
print(my_tuple)
my_result = [{'key': sub[0], 'value': sub[1], 'id': sub[2]}
for sub in my_tuple]
print("The converted dictionary is:")
print(my_result)
The tuple is:
((6, 'Will', 13), (2, 'Mark', 15), (9, 'Rob', 12))
The converted dictionary is:
[{'key': 6, 'value': 'Will', 'id': 13}, {'key': 2, 'value': 'Mark', 'id': 15}, {'key': 9, 'value': 'Rob', 'id': 12}]
Using Descriptive Keys
You can use more descriptive keys to make the data clearer ?
employee_data = ((101, 'Alice', 'Manager'), (102, 'Bob', 'Developer'), (103, 'Carol', 'Tester'))
employees = [{'emp_id': emp[0], 'name': emp[1], 'role': emp[2]}
for emp in employee_data]
print("Employee records:")
for employee in employees:
print(employee)
Employee records:
{'emp_id': 101, 'name': 'Alice', 'role': 'Manager'}
{'emp_id': 102, 'name': 'Bob', 'role': 'Developer'}
{'emp_id': 103, 'name': 'Carol', 'role': 'Tester'}
How It Works
List comprehension iterates through each tuple in the nested tuple
For each sub-tuple, dictionary keys are mapped to specific indices
The result is a list of dictionaries with custom key names
Each dictionary represents one record from the original nested tuple
Conclusion
List comprehension provides an efficient way to convert nested tuples into custom key dictionaries. This approach is ideal for transforming structured data into more readable dictionary format.
