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

Iván Higuera-Mendieta
Iván Higuera-Mendieta
764 Points

Dictionaries Code Challenge

I am sucked at the first Dictionaries Code Challenge. I have been trying the following code:

def members(my_dict, my_list):
  for item in my_list:
     if key in my_dict:
      count = 0
      count += key
     else:
      count = count 
      return count

My intention is to make a count for every item in the list of keys, and this count only will sum if that item is a key in my dictionary, else, this count will be the same.

Am I doing a horrible mistake here?

Thanks in advance.

3 Answers

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

You should move the count variable outside of the loop, also you can simplify the code a little bit

def members(my_dict, my_list):
  count = 0
  for key in my_dict:
    if key in my_list:
      count += 1
  return count

what you are doing with count is nonsensical in my opinion..

btw i think you may need to do: if key in my_dict.keys(): (notice the .keys() at the end!)

Iván Higuera-Mendieta
Iván Higuera-Mendieta
764 Points

Thanks both for the feedback.

I run the code just as William wrote it, it works perfectly. Nonetheless, when you use the if condition, don't you need to use the else condition as well?

shez azr, which approach do you recommend me? I know there is several ways to respond to this challenges.