Q:

Python program to add a dictionary to tuple

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Adding a dictionary to tuple

In this problem, we are given a tuple and a dictionary. We need to create a Python program that will add the dictionary as an element to the tuple.

Input:
('programming', 'language', 'tutorial')
{1 : 'python', 4 : 'JavaScript', 9: 'C++'}

Output:
('programming', 'language', 'tutorial', {1 : 'python', 4 : 'JavaScript', 9: 'C++'})

We need to append the dictionary at the end of the tuple.

This can be done in Python by multiple methods, let's see them in action.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to add a dictionary to a tuple is by using the list addition operation. For this, we will convert a tuple to a list then add append the dictionary at the end of the list and then convert it back to the tuple.

# Python program to add a dictionary to tuple

# Initializing and printing 
# tuple and dictionary
myTuple = ('programming', 'language', 'tutorail')
myDist = {1 : 'python', 4 : 'JavaScript', 9: 'C++'}

print("The elements of tuple are " + str(myTuple))
print("The elements of dictionary are " + str(myDist))

# Adding dictionary to the end of tuple 
myTuple = list(myTuple)
myTuple.append(myDist)
myTuple = tuple(myTuple)

print("Tuple after adding dictionary : " + str(myTuple))

Output:

The elements of tuple are ('programming', 'language', 'tutorail')
The elements of dictionary are {1: 'python', 4: 'JavaScript', 9: 'C++'}
Tuple after adding dictionary : ('programming', 'language', 'tutorail', {1: 'python', 4: 'JavaScript', 9: 'C++'})

Method 2:

One more method to solve the problem is by adding a dictionary to a tuple and then adding the two tuples and returning the new tuple.

# Python program to add a dictionary to tuple

# Initializing and printing 
# tuple and dictionary
myTuple = ('programming', 'language', 'tutorail')
myDist = {1 : 'python', 4 : 'JavaScript', 9: 'C++'}

print("The elements of tuple are " + str(myTuple))
print("The elements of dictionary are " + str(myDist))

# Adding dictionary to the end of tuple 
newTuple = myTuple + (myDist, )

print("Tuple after adding dictionary : " + str(newTuple))

Output:

The elements of tuple are ('programming', 'language', 'tutorail')
The elements of dictionary are {1: 'python', 4: 'JavaScript', 9: 'C++'}
Tuple after adding dictionary : ('programming', 'language', 'tutorail', {1: 'python', 4: 'JavaScript', 9: 'C++'})

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to update each element in the tuple... >>
<< Python program to find the maximum element in tupl...