![]() |
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 PythonBelow, are the ways to create a Dictionary With Tuple As Key Python.
Basic InitializationIn 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
Output
Basic Initialization: {('apple', 1): 'red', ('banana', 2): 'yellow', ('grape', 3): 'purple'} Dictionary With Tuple As Key Using zip() FucntionIn 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
Output
Using zip() Function: {('apple', 1): 'red', ('banana', 2): 'yellow', ('grape', 3): 'purple'} Dictionary With Tuple As Key Using dict() ConstructorIn 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
Output
Using dict() Constructor: {('apple', 1): 'red', ('banana', 2): 'yellow', ('grape', 3): 'purple'} Dictionary With Tuple As Key by Iterating Over ItemsIn 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
Output
Iterating Over Items: ('apple', 1): red ('banana', 2): yellow ('grape', 3): purple |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |