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

oliverchou
oliverchou
20,886 Points

My code works in python IDLE and works for the Example, but I can't pass the challenge!

Here's the code I tested in my IDLE, it works!

test.py
def members(dictionary, li):
    idx = 0
    count = 0
    while idx < len(dictionary):
        if li[idx] in dictionary:
            count += 1
        idx += 1
    return count

#test
my_dict = {'apples': 1, 'bananas': 2, 'coconuts': 3}
my_list = ['apples', 'coconuts', 'grapes', 'strawberries']

print(members(my_dict, my_list))

But I can't pass the challenge! Any idea ?

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(dictionary, li):
    idx = 0
    count = 0
    while idx < len(dictionary):
        if li[idx] in dictionary:
            count += 1
        idx += 1
    return count

1 Answer

Jacob Herrington
Jacob Herrington
15,835 Points

Extremely close to the right answer!

I ran your code locally - and it gave me the right answer! But when I changed the parameters it gave me the wrong answer.

Here is how I found the issue:

my_dict = {'apples': 1, 'bananas': 2, 'coconuts': 3}
my_list = ['apples', 'coconuts', 'grapes', 'strawberries', 'bananas']

I added 'bananas' to my_list and ran this locally - it returned 2, instead of the expected 3.

The problem is that you chose to loop until your counter had reached the length of the dictionary - and that works unless the list is longer than the dictionary. Here is the very slight change to your code, see if you can figure out why this works where your code didn't:

def members(dictionary, li):
    idx = 0
    count = 0
    while idx < len(li):
        if li[idx] in dictionary:
            count += 1
        idx += 1
    return count

Please comment and let me know if you have any questions, I'm happy to explain further.

oliverchou
oliverchou
20,886 Points

I got it! Thanks!