Dictionary with Tuple as Key in Python
Last Updated :
05 Feb, 2024
In Python, dictionaries are versatile data structures that allow you to store and retrieve data efficiently using key-value pairs. While it’s common to use simple types like strings or integers as keys, you can also use more complex data structures, such as tuples. In this article, we’ll explore five different methods to create and manipulate dictionaries with tuples as keys.
Dictionary With Tuple As Key Python
Below, are the ways to create a Dictionary With Tuple As Key Python.
Basic Initialization
In this example, in the below code, a dictionary named tuple_dict is initialized with tuples as keys and corresponding color values. When printed, it displays the key-value pairs representing fruits and their colors.
Python3
tuple_dict = {( 'apple' , 1 ): 'red' , ( 'banana' , 2 ): 'yellow' , ( 'grape' , 3 ): 'purple' }
print ( "Basic Initialization:" )
print (tuple_dict)
|
Output
Basic Initialization:
{('apple', 1): 'red', ('banana', 2): 'yellow', ('grape', 3): 'purple'}
Dictionary With Tuple As Key Using zip() Fucntion
In this example, in below code A dictionary named tuple_dict is created by zipping the keys and values using the zip() function, associating fruits with their colors. When printed, it displays the key-value pairs representing fruits and their colors.
Python3
keys = [( 'apple' , 1 ), ( 'banana' , 2 ), ( 'grape' , 3 )]
values = [ 'red' , 'yellow' , 'purple' ]
tuple_dict = dict ( zip (keys, values))
print ( "\n Using zip() Function:" )
print (tuple_dict)
|
Output
Using zip() Function:
{('apple', 1): 'red', ('banana', 2): 'yellow', ('grape', 3): 'purple'}
Dictionary With Tuple As Key Using dict() Constructor
In this example, in below code A dictionary named tuple_dict is constructed using the dict() constructor with a list of tuple-key-value pairs. When printed, it shows the key-value pairs representing fruits and their colors.
Python3
tuple_dict = dict ([(( 'apple' , 1 ), 'red' ), (( 'banana' , 2 ), 'yellow' ), (( 'grape' , 3 ), 'purple' )])
print ( "\n Using dict() Constructor:" )
print (tuple_dict)
|
Output
Using dict() Constructor:
{('apple', 1): 'red', ('banana', 2): 'yellow', ('grape', 3): 'purple'}
Dictionary With Tuple As Key by Iterating Over Items
In this example, in below code iterates over the items in the tuple_dict dictionary, printing each key-value pair in the format “key: value” for fruits and their corresponding colors.
Python3
tuple_dict = {( 'apple' , 1 ): 'red' , ( 'banana' , 2 ): 'yellow' , ( 'grape' , 3 ): 'purple' }
print ( "\n Iterating Over Items:" )
for key, value in tuple_dict.items():
print (f "{key}: {value}" )
|
Output
Iterating Over Items:
('apple', 1): red
('banana', 2): yellow
('grape', 3): purple
Share your thoughts in the comments
Please Login to comment...