In this article, we will discuss how to Iterate over Tuples in Dictionary in Python.
Method 1: Using index
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:
# 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.
Method 2 : Using values() method
we can use dictionary.values() to iterate over the tuples in a dictionary with for loop
Syntax:
for i in dictionary_name.values(): for j in i: print(j) print(" ")
Example:
# Initializing a dictionary myDict = { 1 : ( "Apple" , "Boy" , "Cat" ),
2 : ( "Geeks" , "For" , "Geeks" ),
3 : ( "I" , "Am" , "Learning" , "Python" )}
# iterate over all tuples using # values() method for i in myDict.values():
for j in i:
print (j)
print ( " " )
|
Output:
Apple Boy Cat Geeks For Geeks I Am Learning Python
Time complexity: O(n^2) where n is the number of tuples in the dictionary.
Auxiliary space: O(1)
Method 3 : Using items() and * operator
# Initializing a dictionary myDict = { 1 : ( "Apple" , "Boy" , "Cat" ),
2 : ( "Geeks" , "For" , "Geeks" ),
3 : ( "I" , "Am" , "Learning" , "Python" )}
# iterate over all tuples using # items() method for key, tupleValues in myDict.items():
print ( * tupleValues)
|
Apple Boy Cat Geeks For Geeks I Am Learning Python
Time Complexity: O(n), where n is the values in dictionary
Auxiliary Space: O(1), constant extra space required