Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python – Create Dictionary Of Tuples

  • Last Updated : 10 Oct, 2021

In this article, we will discuss how to create a dictionary of tuples in Python.

Dictionary of tuples with tuples as keys

Here we will pass keys as tuples inside a dictionary

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Syntax:



{(tuple1):value,(tuple2):value,.........,(tuple3):value}

Here tuple is a collection of elements that work as a key for some value

Example: Python program to create a dictionary of tuples with a tuple as keys

Python3




# tuple of favourite food as key
# value is name of student
data = {("chapathi", "roti"): 'Bobby'
        ("Paraota", "Idly", "Dosa"): 'ojaswi'}
  
# display
data

Output:

{('Paraota', 'Idly', 'Dosa'): 'ojaswi', ('chapathi', 'roti'): 'Bobby'}

Dictionary of tuples with tuples as values

Here we will pass values as tuples inside a dictionary

Syntax:

{key:(tuple),key :(tuple2).........,key:(tuple)}

Here tuple is a collection of elements that represent some value for some key.

Example: Python program to create dictionary of tuples with tuple as values

Python3




# tuple of favourite food as value
# key is name of student
data = {'Bobby': ("chapathi", "roti"), 
        'ojaswi': ("Paraota", "Idly", "Dosa")}
  
# display
data

Output:

{'Bobby': ('chapathi', 'roti'), 'ojaswi': ('Paraota', 'Idly', 'Dosa')}

Create a dictionary from tuples

Here we will create a dictionary from nested tuples and for that we need to pass two values in each tuple one will represent key and the other its corresponding value in the dictionary.

Syntax:

dict((value, key) for key,value in nested_tuple)

Example: Create a dictionary from tuples

Python3




# one value is age of student
# second value is student name
data = ((24, "bobby"), (21, "ojsawi"))
  
# convert into dictionary
final = dict((value, key) for key, value in data)
  
# display
print(final)

Output:

{'bobby': 24, 'ojsawi': 21}



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!