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

Nick Smith
Nick Smith
6,688 Points

This works in workspace but not on submission page.

def members(dic, keys): count = 0 for i in list: if i in dic: count+=1 return count

dict = {'apples':1, 'bananas': 2, 'coconuts':3, 'tacos':1} list= ['apples', 'coconuts', 'strawberries', 'oranges', 'tacos']

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

2 Answers

def members(dic, keys):
    count = 0
    # for i in list:  # list is not defined, so you can't loop through it. I'm surprised this worked in workspaces.
    for i in keys:
        if i in dic:
            count+=1 
    return count
# Because I like list comprehension, this works too.
def members(dictionary, keys):
    return len([key for key in keys if key in dictionary])
Hara Gopal K
PLUS
Hara Gopal K
Courses Plus Student 10,027 Points

i was wondering why this shouldn't work ?

def members (my_dict, my_list): return len (my_list) return my_dict.keys ()

Nick Smith
Nick Smith
6,688 Points

You need a for loop to count key/value. Also you have two return statements. Once it reaches the first return statement, the code stops running and returns that value. So it will never get to your my_dict.keys ()