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 studentdata = {("chapathi", "roti"): 'Bobby', ("Paraota", "Idly", "Dosa"): 'ojaswi'} # displaydata |
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 studentdata = {'Bobby': ("chapathi", "roti"), 'ojaswi': ("Paraota", "Idly", "Dosa")} # displaydata |
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 namedata = ((24, "bobby"), (21, "ojsawi")) # convert into dictionaryfinal = dict((value, key) for key, value in data) # displayprint(final) |
Output:
{'bobby': 24, 'ojsawi': 21}
