Convert Nested Tuple to Custom Key Dictionary in Python

When it is required to convert a nested tuple into a customized key dictionary, the list comprehension can be used.

Below is the demonstration of the same −


 Live Demo

my_tuple = ((6, 'Will', 13), (2, 'Mark', 15), (9, 'Rob', 12))

print("Thw tuple is : ")

my_result = [{'key': sub[0], 'value': sub[1], 'id': sub[2]}
   for sub in my_tuple]

print("The converted dictionary is : ")


Thw 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}]


  • A tuple of tuple is defined, and is displayed on the console.

  • The list comprehension is used to iterate over the tuple.

  • The key and value in the dictionary is assigned certain value, along with a specific id.

  • This is assigned to a variable.

  • It is displayed as output on the console.