Skip to content
Related Articles

Related Articles

Python – Create Dictionary Of Tuples

Improve Article
Save Article
  • Last Updated : 10 Oct, 2021
Improve Article
Save Article

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

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
Related Articles

Start Your Coding Journey Now!