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

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