Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Siddhant Shrivastav
17,320 PointsCan someone please explain why this code throws an error?
I understand that looping through the dictionary and conditionally checking the list for common key values is the better way to do it. I'd just like some input on why this way is not working as I expected it to.
# You can check for dictionary membership using the
# "key in dict" syntax from lists.
### Example
def members(a_dict, a_list):
count = 0
for items in a_list:
if items == a_dict[items]:
count += 1
return count
my_dict = {'apples': 1, 'bananas': 2, 'coconuts': 3}
my_list = ['apples', 'coconuts']
members(my_dict, my_list)
1 Answer

Hanley Chan
27,771 PointsHi,
Your if condition appears to be incorrect. For example in your example list and dictionary during the first iteration of your for loop the variable items would be 'apples'. Your if condition would then check if 'apples' == a_dict['apples'], but a_dict['apples'] = 1. So you are comparing if 'apples' == 1.
Siddhant Shrivastav
17,320 PointsSiddhant Shrivastav
17,320 PointsThanks a bunch.