
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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.
Advertisements