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

How do i do that, I am confused

Write a function named members that takes two arguments, a dictionary and a list of keys. Return a count of how many of the items in the list are also keys in the dictionary.

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(dict1,list1):

4 Answers

Matthew Hill
Matthew Hill
7,799 Points

Hi Dima, here's my solution. I think it's easier if you just loop through the items in the list and check for membership in the dictionary.

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

Let me know if that makes sense or not! Matt

Matthew Hill
Matthew Hill
7,799 Points

It always helps to have another watch of the video, or maybe do a search online (sites such as stack overflow are usually very helpful), this way you can have some extra help figuring it out for yourself so you'll learn more than if I just gave you the answer.

As a hint try iterating through your list using:

for item in list:
    # Do something here

Hope that helps! Matt

I wrote this code but it still incorrect, what can I do?

count=0 index=0 def members(dict1,list1): for item in dict1: if item==list1[index]: count=count+1 index=index+1 else: index=index+1 continue print(count)

Thank you very much, it was far more simple then what I tried to do