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

Why is my members() function returning 0?

The challenge is as follows: Write a function named members that takes 2 arguments, a dictionary and a list of keys. Return a count of how many items in the list are also keys in the dictionary.

Can someone please tell me what is wrong with my code? thanks!

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(listy, dicto):
  answer = 0
  for key in dicto:
    count = 0
    while count < len(listy):
      if key == listy[count]:
        answer +=1
      count +=1
  return answer

3 Answers

Dan Johnson
Dan Johnson
40,533 Points

Your code is fine, you just have your positional arguments flipped. The challenge expects the dictionary first and the list second.

Also if you want to avoid having nested loops you can use the in keyword to check the contents of the list:

if key in listy:
  answer +=1

Thanks for the quick response. Why are my positional arguments flipped?

Dan Johnson
Dan Johnson
40,533 Points

They're flipped since the challenge is going to be passing in the dictionary first, and then the list. The last line of the comments shows how it'll be called:

# members(my_dict, my_list) => 2

Right ... just flipped it and it worked. thanks!!!