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

Python Python Collections (Retired) Dictionaries Membership

Siddhant Shrivastav
Siddhant Shrivastav
17,320 Points

Can 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.

counts.py
# 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
Hanley Chan
27,771 Points

Hi,

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.