I'm trying to run a nested for loop with a conditional statement. When running it, I expect it to print the statement that I defined if my conditional statement. But it doesn't print anything. (and it doesn't run indefinitely). Pokemons_gyms is a list of strings. Players is a dictionary. I tried adding else: continue but it doesn't work. I'm stuck cause I don't get any error running the code...
pokemon_gyms = ['reddit.com', 'amazon.com', 'twitter.com',
'linkedin.com', 'ebay.com','netflix.com',
'udacity.com','stackoverflow.com','github.com',
'quora.com']
players= {
1: {
'gyms_visited': ['amazon.com', 'ebay.com']
}
2:{
'gyms_visited' : ['stackoverflow.com','github.com']
}
}
for gym in pokemon_gyms:
for players_id in players:
if gym == players[players_id]['gyms_visited']:
print(str(players[players_id]['player_name']) +" has visited "+ str(gym))
4 Answers 4
players[players_id]['gyms_visited'] returns a list so gym == players[players_id]['gyms_visited'] always evaluates to False.
You should check for membership using in:
if gym in players[players_id]['gyms_visited']:
...
3 Comments
__getitem__ is going to return, so there is a return value here, it's just not so explicit.The problem here is that gym is going to be a str while players[players_id]['gyms_visited'] is a list of strings. Because of this, they will never be equal.
Perhaps you want to check
if gym in players[players_id]['gyms_visited']:
Comments
Your problem is in the line if gym == players[players_id]['gyms_visited']:. == checks for equality so this will look if gym is equal to the list in players[players_id]['gyms_visited'] in the dictionary.
If you want to check if the any of the items in the list is equal to the string you can use the in keyword
for gym in pokemon_gyms:
for players_id in players:
if gym in players[player_id]['gyms_visited']:
# Do things here
Notice that for large lists this can be rather slow so you might want to consider using a set instead if you are going to have players with lots of visited pokemon_gyms.
Comments
YUP! All set, it was '==' that was resulting to all results being False because of type(gym) is different from type(players[players_id]['gyms_visited']).
I replaced '==' by 'in' and it worked perfectly.
Thank you guys!
1 Comment
Explore related questions
See similar questions with these tags.