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

membership

def members(my_dict, my_list): same = [] for item in my_list: for key in my_dict: if item == key: same += item return len(same)

The 'answer' was wrong, because it was 'expecting 2, but got 19.' So I changed the last line to return same so that I could see the list. Instead of getting (apples, coconuts), I got ('f', 'i', 'r', 's', 't', '', 'n', 'a', 'm', 'e', 'l', 'a', 's', 't', '', 'n', 'a', 'm', 'e'). Did I write bad code, or is it somehow referencing the wrong my_dict and my_list? Maybe somehow connected to my workspace?

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(my_dict, my_list):
  same = []
  for item in my_list:
    for key in my_dict:
      if item == key:
        same += item
  return same

1 Answer

Dan Johnson
Dan Johnson
40,532 Points

On a list, += is shorthand for extend, so it'll break up the string and then add each element. So to add the string as a whole rather than its individual elements, you could go with:

same.append(item)

Alternatively you can avoid using lists to count elements and have same be an integer initialized to 0. Then just check for inclusion in the dictionary:

if item in my_dict:
    same += 1