
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
Add Dictionary to Tuple in Python
When it is required to add a dictionary to a tuple, the 'list' method, the 'append', and the 'tuple' method can be used.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
The 'append' method adds elements to the end of the list.
Below is a demonstration of the same −
Example
my_tuple_1 = (7, 8, 0, 3, 45, 3, 2, 22, 4) print ("The tuple is : " ) print(my_tuple_1) my_dict = {"Hey" : 11, "there" : 31, "Jane" : 23} print("The dictionary is : ") print(my_dict) my_tuple_1 = list(my_tuple_1) my_tuple_1.append(my_dict) my_tuple_1 = tuple(my_tuple_1) print("The tuple after adding the dictionary elements is : ") print(my_tuple_1)
Output
The tuple is : (7, 8, 0, 3, 45, 3, 2, 22, 4) The dictionary is : {'Hey': 11, 'there': 31, 'Jane': 23} The tuple after adding the dictionary elements is : (7, 8, 0, 3, 45, 3, 2, 22, 4, {'Hey': 11, 'there': 31, 'Jane': 23})
Explanation
- A tuple is defined and is displayed on the console.
- A dictionary is defined and is displayed on the console.
- The tuple is converted to a list, and the dictionary is added to it using the 'append' method.
- Then, this resultant data is converted to a tuple.
- This result is assigned to a value.
- It is displayed as output on the console.
Advertisements