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

John Schut
John Schut
2,317 Points

counts.py asigment

See please my solution below.

It returns 0 in stead of 2.

It has maybe to do with the fact that a list-item is not the same datatype as the key of a dictionary...(?)

# 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

my_dict = {'apples': 1, 'bananas': 2, 'coconuts': 3}
my_list = ['apples', 'coconuts', 'grapes', 'strawberries']

def members(dictionary, mylist):
  count = 0
  for item in mylist:
          if dictionary[item] in [1,2,3]:
              count += 1


members(my_dict, my_list)

5 Answers

Steven Parker
Steven Parker
229,981 Points

Here's a few hints:

  • you don't need to define a dict or list, the challenge will use its own for testing
  • you only need to define your function, not call it
  • don't print the result, only return it
  • don't assume anything about the contents of the dictionary (don't compare against literal values)
  • remember, you're checking for keys not values
  • try checking each item in the list to see if it is in the dictionary.keys()

I'm betting you can get it now without an explicit spoiler.

John Schut
John Schut
2,317 Points

Hi Steven, thanks! I will have a second try.

John Schut
John Schut
2,317 Points

Hi Steven, can you please send the code? I am done trying, it's not motivating to try any longer. I will learn enough from seeing the code. Thanks upfront!

Hey John, i too was confused. I had to read the question over and over.

def members(my_dict, my_list):
  count = 0
  for item in my_dict:
    if item in my_list:
      count += 1
  return count
John Schut
John Schut
2,317 Points

Hi Mazen,

Thanks for your response.