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

Malcolm Robertson
Malcolm Robertson
8,478 Points

Correct Answer outside def, what am I doing wrong?

Hi,

Reference Challenge 1 of 1 Dictionaries Membership

I must be having issues understanding functions, the layout and rules on calling them.

I can run the below code and get the answer to to the challenge but when I try to put the code into a def I get errors.

Code outside a def

my_dict = {'apples': 1, 'bananas': 2, 'coconuts': 3}
my_list = ['apples', 'coconuts', 'grapes', 'strawberries']
for name in my_dict and my_list:
    if name in my_dict and my_list:
        print(name)
    else:
        print("Else Print")
        break

When I put the above into a def as below I get a error (Bummer! Expected 2, got apples.):

def members(adict, alist):
    my_dict = {'apples': 1, 'bananas': 2, 'coconuts': 3}
    my_list = ['apples', 'coconuts', 'grapes', 'strawberries']
    for name in my_dict and my_list:
        if name in my_dict and my_list:
            print(name)
            return(name)
        else:
            print("Else Print")
            continue
    members(my_dict, my_list)

Any help would be much appreciated.

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Try removing this line and see what happens:

return(name)

This would explain why you're returning apples instead of 2.

Malcolm Robertson
Malcolm Robertson
8,478 Points

Jennifer, I removed the return(name) and I am now getting Bummer! Try again!

I presume this approach I am taking is not valid.

1 Answer

Idan Melamed
Idan Melamed
16,285 Points

Hi Malcolm

I've noticed a few things:

  1. The challenge asks you to count and return how many times the items in the list are also keys in the dictionary.
  2. You don't need to assign my_list and my_dict
  3. You also don't need to call the function
  4. I would try to change the for loop and if statement to check only in one variable. For example, my for loop would be: for word in my_list:

If you want to see a solution, you can check out this link: https://trinket.io/python/a803c750e9

Malcolm Robertson
Malcolm Robertson
8,478 Points

Hi Idan,

I see what you mean.

Thanks for your help.