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

Kody Dibble
Kody Dibble
2,554 Points

How to write the function Python Challenge my_dict my_list

So I can't figure out how to use this code, I made the function and then the for and if statements along with the throwaway variable...

Not sure, been asking a lot of questions lately ! Thanks!

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, 'peaches': 5}
my_list = ['apples', 'bananas', 'peaches']

def members(my_dict, my_list): 

  counts = 0
for item in my_list:
if item in my_dict.keys():

    counts += 1

  return counts

4 Answers

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

Your code is all correct, only thing is that you need to fix the indentation. White spaces and indentation are of syntactic importance in Python.

def members(my_dict, my_list): 
    counts = 0
    for item in my_list:
        if item in my_dict.keys():
            counts += 1
    return counts
Kody Dibble
Kody Dibble
2,554 Points

So how does Python know what item means? Does it know what key means as well?

William Li
William Li
Courses Plus Student 26,868 Points

item is just a name given to the loop variable, you can give it any name you want, you don't have to always name it item.

This blog post https://blog.udemy.com/python-for-loop/ does a great job at explaining Python's for loop.

Kody Dibble
Kody Dibble
2,554 Points

The code still didn't work... Not sure whats up.

Kody Dibble
Kody Dibble
2,554 Points

Hmmm how does it know where to take the list? Or does the example think it already has it.