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


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.

# 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']
if my_list == my_dict['apples','bananas','coconuts']
    return count
members(my_dict, my_list) 

3 Answers

wang yang
wang yang
Courses Plus Student 1,728 Points
def members(my_dict, my_list):
    counts = 0
    for key in my_dict:
        counts += my_list.count(key)
    return counts
Cindy Lea
Cindy Lea
Courses Plus Student 6,497 Points

Heres one way you can do it:

def members(d, l): count = 0

for item in l: if d.get(item, None): count = count + 1 return count

Hey found it some_dict = {'a': 1, 'b': 2, 'c': 3}

key_list = ['a', 'b', 'd']

def members(some_dict, key_list):

counts = 0

for item in key_list:

if item in some_dict.keys():

  counts += 1

return counts