Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (Retired) Dictionaries Membership

dictionary

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

3 Answers

wang yang
PLUS
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
PLUS
Cindy Lea
Courses Plus Student 6,485 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