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

Live Demo

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.

Updated on: 11-Mar-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements