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

Bob Amand
Bob Amand
2,639 Points

Counts.dy; can the key() values be converted to a list?

Is my strategy good? I attempted to convert the dictionary keys into a list of keys. Then I thought I could just count those that are equal to the list. Not working. I think I am missing a fundamental characteristic of the dictionary. Any clues would be helpful. 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
def members(mydic,mylst):
  count =0
  inter = list(mydic.keys())
  for i in mylst:
    if i = inter[i]:
      count += 1
  return count

1 Answer

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Ultimately, you're doing an intersection. You want to see where these two items overlap. Your approach is OK (mydic.keys() is already an iterable so you don't have to make it a list in order to be able to do a for loop with it) but I see two things.

  • if i = inter[i] is gonna fail because you can't do assignment in an if
  • if i in inter would be a much better check because that tests whether or not i is in inter.