

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- Python Convert nested dictionary into flattened dictionary?
- Python - Convert flattened dictionary into nested dictionary
- Python – Concatenate Tuple to Dictionary Key
- Python - Convert List to custom overlapping nested list
- Convert tuple to adjacent pair dictionary in Python
- 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?
- Add dictionary to tuple in Python
- How to create nested Python dictionary?
- How can I convert a Python Named tuple to a dictionary?
- Convert string dictionary to dictionary in Python
- How to sort a nested Python dictionary?
- How to convert Javascript dictionary to Python dictionary?
Advertisements