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

Trevor Wood
Trevor Wood
17,828 Points

Not sure what Im doing wrong here

I tested it in workspaces and it returns the correct number, but the objective keeps on telling me it expected a different number.

counts.py
# You can check for dictionary membership using the
# "key in dict" syntax from lists.

### Example
# my_dict = {'apples': 1, 'bananas': 2, 'coconuts': 3}
# my_list = ['apples', 'coconuts', 'grapes', 'strawberries']
# members(my_dict, my_list) => 2

def members(a,b):
  count = 0
  for a in b:
    count = count+1
  return count

my_dict = {'foo':1,'bar':2,'zoo':3,'derp':4}
my_list = {'foo','bar'}

members(my_dict,my_list)

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

There are a few things going on here. First and foremost, you don't get to decide what the dictionary and key list look like. Treehouse is going to do that. They're going to send in some unknown information to test your code. Secondly, the "b" variable holds a list of keys. We're going to go down that list and then check if that key is also in the dictionary which is stored in the variable a. So what we need to do is set up a for loop to check all of b. Then check each item in b against a. Take a look at my solution and see if it makes sense.

def members(a,b):
  count = 0
  for key in b:
    if key in a:
      count = count + 1
  return count

First, I define the members function. Set count to 0. Then for every key in b I check to see if that key is also in a (which is the dictionary). If it is, then we increment count. Finally, we return the total. Hope this helps!

Trevor Wood
Trevor Wood
17,828 Points

ah okay I see, I thought for some reason a in b was comparing it directly.