+

Python | Add dictionary to tuple

Method # 1: Using list () + append + tuple ()
This method can be used to solve this problem. In this case, we simply convert the tuple to a list, then add to the list, and then convert the list to a tuple using tuple ().

# Python3 demo code work
# Add dictionary to tuple
# using append () + tuple () + comprehension list

 
# initialize tuple

test_tup = ( 4 , 5 , 6 )

 
# printing original tuple

 print ( "The original tuple:" + str (test_tup))

 
# initialize dictionary

test_dict = { "gfg" : 1 , "is" : 2 , " best " : 3 }

 
# Add dictionary to tuple
# using append () + tuple () + comprehension list

test_ tup = list (test_tup)

test_tup.append (test_dict)

test_tup = tuple (test_tup)

 
# print result

print ( "Tuple after addition of dictionary:" + str (test_tup))

Output:

 The original tuple: (4, 5, 6) Tuple after addition of dictionary: (4, 5, 6, {`best`: 3,` is`: 2, `gfg`: 1}) 

Method # 2: Using the + operator
This is another way to accomplish this task. In this, we add a dictionary to another tuple and then add the old tuple to that tuple and form a new tuple. The key difference is that this is not an in-place addition as the top method, but a creation of a new tuple from the old one.

# Python3 code to demonstrate how it works
# Add a dictionary to the tuple
# using the + operator

 
# initialize tuple

test_tup = ( 4 , 5 , 6 )

 
# print original tuple

print ( " The original tuple: " + str (test_tup) )

 
# initialize dictionary

test_dict = { "gfg " : 1 , " is " : 2 , "best" : 3 }

 
# Add dictionary to tuple
# using the + operator

res = test_tup + (test_dict,)

  
# print result

print ( "Tuple after addition of dictionary:" + str (res))

Output:

 The original tuple: (4, 5, 6) Tuple after addition of dictionary: (4, 5, 6, {`best`: 3,` is`: 2, `gfg`: 1}) 
Get Solution for free from DataCamp guru