Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Deactivated Account
673 PointsWeird 'gender' error in Membership challenge for python collections.
I tried to write code for first challenge which worked fine in my local environment but it is giving me this weird 'gender' error in treehouse.
Also if item from list2 is not in dict2 then it give me KeyError : item. Isn't IF condition I wrote must be checking for its absence then skipping it to ELSE?
def members(dict2, list2):
count = 0
for item in list2:
if dict2[item]:
count = count + 1
else:
continue
return(count)
3 Answers
Chris Freeman
Treehouse Moderator 68,468 PointsYour code is very close. Instead of looking up the item from list in the dictionary (which might cause a KeyError if not found), simply check if the item is in the list of dictionary keys:
def members(dict2, list2):
count = 0
for item in list2:
if item in dict2: # <-- changed key search. same as "if item in dict2.keys()"
count = count + 1
else:
continue
return(count)
I also saw the weird Bummer! 'gender' error message with your original code. Tagging Kenneth Love for comment.
Evan Demaris
64,262 PointsHi Shubhanshu,
I'd recommend running through the items in the dictionary instead of the list; ex.
def members(dict2, list2):
count = 0
for item in dict2:
if item in list2:
count += 1
return count
In terms of the gender error you're describing, could you include the full text of the error, or a screenshot?
Chris Freeman
Treehouse Moderator 68,468 PointsOne downside to using item in dict2 as the outer loop, is if dict2 is very large the loop runs many more times verses using list2 as the outer which runs the number of items in list2
Evan Demaris
64,262 PointsThat's a good point; efficiency is important!
Kenneth Love
Treehouse Guest TeacherThe 'gender' error was a KeyError I wasn't catching (the challenge has been updated to catch that now).