+ 1

Testing if value exists in a dictionary

I was just wondering how would I be able test if the person is in the clubs dictionary. clubs = {"basketball":[], "volleyball":[], "football":[]} clubs["basketball"].append("John") print(clubs) #asking user for name name = input("Enter a name.") if name in clubs.values(): print(name, "is in a club") else: print(name, "is not in a club") when name = John it prints saying “John is not in a club” but he is in the basketball club? How would I be able to fix this? Thank you :)

7th Aug 2019, 10:41 AM
Luna
6 odpowiedzi
+ 5
may be this can help you for dict update: https://code.sololearn.com/cRkp6lrEtxb4/?ref=app
7th Aug 2019, 1:08 PM
Lothar
Lothar - avatar
+ 3
Because you are using lists as the clubs values, the interpreter sees them as lists "John" != ["John"] You could fix it like this https://code.sololearn.com/c0AnoT98vnVR/?ref=app
7th Aug 2019, 10:50 AM
Trigger
Trigger - avatar
+ 3
clubs = {"basketball":[], "volleyball":[], "football":[]} clubs["basketball"].append("John") print(clubs) #asking user for name name = "John" if name in clubs["basketball"]: print(name, "is in a club") else: print(name, "is not in a club")
7th Aug 2019, 10:52 AM
Steven M
Steven M - avatar
+ 3
An alternative approach without using a loop: from itertools import chain name = "John" if name in chain.from_iterable(clubs.values()): print(f"{name} is in a Club")
7th Aug 2019, 11:39 AM
Tibor Santa
Tibor Santa - avatar
+ 3
Check out the update() method, I think that will work https://www.w3schools.com/JUMP_LINK__&&__python__&&__JUMP_LINK/ref_dictionary_update.asp something like this might help you out as well... https://code.sololearn.com/cqbZK7wU8zLQ/?ref=app
7th Aug 2019, 12:36 PM
Steven M
Steven M - avatar
+ 1
thanks everyone :) is there a way to add a person to a club for example, name = input(“enter a name”) then that name can be appended to an existing team of their choice?
7th Aug 2019, 12:24 PM
Luna