How to use index In Python
We can get the particular tuples by using an index:
Syntax:
dictionary_name[index]
To iterate the entire tuple values in a particular index
for i in range(0, len(dictionary_name[index])): print(dictionary_name[index][i]
Example:
Python
# Initializing a dictionary myDict = { 1 : ( "Apple" , "Boy" , "Cat" ), 2 : ( "Geeks" , "For" , "Geeks" ), 3 : ( "I" , "Am" , "Learning" , "Python" )} print ( "Tuple mapped with the key 1 =>" ), # Directly printing entire tuple mapped # with the key 1 print (myDict[ 1 ]) print ( "Tuple mapped with the key 2 =>" ), # Printing tuple elements mapped with # the key 2 one by one for each in myDict[ 2 ]: print (each), print ("") print ( "Tuple mapped with the key 3 =>" ), # Accessing tuple elements mapped with # the key 3 using index for i in range ( 0 , len (myDict[ 3 ])): print (myDict[ 3 ][i]), |
Output:
Tuple mapped with the key 1 => ('Apple', 'Boy', 'Cat') Tuple mapped with the key 2 => Geeks For Geeks Tuple mapped with the key 3 => I Am Learning Python
Time complexity: O(1) for accessing a tuple by key and O(n) for iterating through a tuple using index.
Auxiliary space: O(1) as no extra space is used, only the dictionary and variables are used.
Python – Iterate over Tuples in Dictionary
In this article, we will discuss how to Iterate over Tuples in Dictionary in Python.
Contact Us