Python – Iterate over Tuples in Dictionary
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:
Python
myDict = { 1 : ( "Apple" , "Boy" , "Cat" ),
2 : ( "Geeks" , "For" , "Geeks" ),
3 : ( "I" , "Am" , "Learning" , "Python" )}
print ( "Tuple mapped with the key 1 =>" ),
print (myDict[ 1 ])
print ( "Tuple mapped with the key 2 =>" ),
for each in myDict[ 2 ]:
print (each),
print ("")
print ( "Tuple mapped with the key 3 =>" ),
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:
Python3
myDict = { 1 : ( "Apple" , "Boy" , "Cat" ),
2 : ( "Geeks" , "For" , "Geeks" ),
3 : ( "I" , "Am" , "Learning" , "Python" )}
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
Python3
myDict = { 1 : ( "Apple" , "Boy" , "Cat" ),
2 : ( "Geeks" , "For" , "Geeks" ),
3 : ( "I" , "Am" , "Learning" , "Python" )}
for key, tupleValues in myDict.items():
print ( * tupleValues)
|
Output
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
Last Updated :
27 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...