
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
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 −
Example
my_tuple = ((6, 'Will', 13), (2, 'Mark', 15), (9, 'Rob', 12)) print("Thw 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)
Output
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}]
Explanation
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.
- Related Articles
- Python – Concatenate Tuple to Dictionary Key
- Python Convert nested dictionary into flattened dictionary?
- Python - Convert flattened dictionary into nested dictionary
- Convert tuple to adjacent pair dictionary in Python
- Python - Convert List to custom overlapping nested list
- Python Pandas - Convert Nested Dictionary to Multiindex Dataframe
- Convert key-values list to flat dictionary in Python
- Python - Convert list of nested dictionary into Pandas Dataframe
- How I can convert a Python Tuple into Dictionary?
- How can I convert a Python Named tuple to a dictionary?
- Add dictionary to tuple in Python
- How to create nested Python dictionary?
- Convert string dictionary to dictionary in Python
- How to sort a nested Python dictionary?
- Dictionary to list of tuple conversion in Python

Advertisements