Dictionary with Tuple as Key in Python
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
- Using zip() Function
- Using dict() Constructor
- Iterating Over Items
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
# Basic Initialization tuple_dict = {( 'apple' , 1 ): 'red' , ( 'banana' , 2 ): 'yellow' , ( 'grape' , 3 ): 'purple' } print ( "Basic Initialization:" ) print (tuple_dict) |
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
# Using zip() Function 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) |
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
# Using dict() Constructor tuple_dict = dict ([(( 'apple' , 1 ), 'red' ), (( 'banana' , 2 ), 'yellow' ), (( 'grape' , 3 ), 'purple' )]) print ( "\n Using dict() Constructor:" ) print (tuple_dict) |
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
# Iterating Over Items 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}" ) |
Iterating Over Items: ('apple', 1): red ('banana', 2): yellow ('grape', 3): purple
Contact Us