Python | Add dictionary to tuple

Sometimes, while working with data, we can have a problem in which we need to append to a tuple a new record which is of form of Python dictionary. This kind of application can come in web development domain in case of composite attributes. Let’s discuss certain ways in which this task can be performed.

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Add dictionary to tuple
# using append() + tuple() + list comprehension
  
# 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() + list comprehension
test_tup = list(test_tup)
test_tup.append(test_dict)
test_tup = tuple(test_tup)
  
# printing result
print("Tuple after addition of dictionary : " + str(test_tup))

chevron_right


Output :



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

 

Method #2 : Using + operator
This is another way to perform this task. In this, we add dictionary to different tuple and then add the old tuple to this tuple and form new tuple. Key difference is that this is not inplace addtion as upper method, but creates new tuple out of old one.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Add dictionary to tuple
# using + operator
  
# 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 + operator
res = test_tup + (test_dict, )
  
# printing result
print("Tuple after addition of dictionary : " + str(res))

chevron_right


Output :

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.