Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Python – Iterate over Tuples in Dictionary

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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




# 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:

Python3




# 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 

Python3




# 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)

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


My Personal Notes arrow_drop_up
Last Updated : 27 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials