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

sidni ahmed
sidni ahmed
3,329 Points

Write a function named members

can someone please help me with this? i'm just confused what to do in the function part

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

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

  def members(my_dict, my_list):

3 Answers

Seth Reece
Seth Reece
32,867 Points

Hi Sidni,

What you want here is to loop through the keys in a dictionary and check if they are also in the list. e.g.

def members(my_dict, my_list):
  x = 0
  for key in my_dict:
    if key in my_list:
      x += 1
  return x
sidni ahmed
sidni ahmed
3,329 Points

what i don't get is why x = 0. the we do x += 1. what is going on here? its puzzling

Seth Reece
Seth Reece
32,867 Points

Every time a key in my_dict is found in my_list we increment x to return a count of matching items.

sidni ahmed
sidni ahmed
3,329 Points

i'm sorry to bother you, but one quick question. it's just that how is it that if i add keys in the dictionary that are in the list. How does the function know which keys are the same? I understand we increment x to return matching items, but how does it even know the items are even matching? i think i maybe confusing myself her

Seth Reece
Seth Reece
32,867 Points

In this loop we go through all they keys in my-dict one at a time. That key is stored in the variable key. Then check if it's in my_list. If it is increase x by one.