En este artículo, discutiremos cómo iterar sobre tuplas en el diccionario en Python.
Método 1: usar el índice
Podemos obtener las tuplas particulares usando un índice:
Sintaxis:
dictionary_name[index]
Para iterar los valores completos de la tupla en un índice particular
for i in range(0, len(dictionary_name[index])): print(dictionary_name[index][i]
Ejemplo:
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]),
Producción:
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
Método 2: Usar el método de valores()
podemos usar dictionary.values() para iterar sobre las tuplas en un diccionario con bucle for
Sintaxis:
for i in dictionary_name.values(): for j in i: print(j) print(" ")
Ejemplo:
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(" ")
Producción:
Apple Boy Cat Geeks For Geeks I Am Learning Python