+ 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 :)
6 Answers
+ 5
may be this can help you for dict update:
https://code.sololearn.com/cRkp6lrEtxb4/?ref=app
+ 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
+ 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")
+ 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")
+ 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
+ 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?