+ 1

How to read tuple in list (Python)

How can I solve the problem? In the tuple is a dictonary. How I can reach the number of a value? contacts = [ ('James', 42), ('Amy', 24), ('John', 31), ('Amanda', 63), ('Bob', 18) ] x = input() print(x, "is", [(x)])

12th Dec 2023, 4:33 PM
Andreas Heil
Andreas Heil - avatar
4 Respostas
+ 7
Andreas Heil , what we have here is a *list* (named contacts) that contains 5 *tuples*. (no dictionary) > to get the tuples and its content, we need to iterate over the list. > when using a for lopp, we get *one tuple at a time* in a variable. > to get the content of the tuple, we can use the index notation. using index [0] gets the name, index [1] gets the age.
12th Dec 2023, 4:53 PM
Lothar
Lothar - avatar
+ 4
@Andreas Heil , that looks great!
12th Dec 2023, 6:54 PM
Lothar
Lothar - avatar
+ 3
iterate the list. on esch iteration, check if name is the one you are looking for.
12th Dec 2023, 4:52 PM
Lisa
Lisa - avatar
+ 1
Thank you both for your help. Now it works. contacts = [ ('James', 42), ('Amy', 24), ('John', 31), ('Amanda', 63), ('Bob', 18) ] name = input() for x in contacts: if name in x: print(str(x[0]) +" is " + str(x[1])) break else: print("Not Found")
12th Dec 2023, 6:06 PM
Andreas Heil
Andreas Heil - avatar