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 trialBrian Hartley
3,115 PointsLoop returning 3x the number that it should
Something is strange with this challenge. The 'for key in dict' loop is seeing all items in a dictionary as keys. For example, the following functions return 9 in the Challenge workspace, which is incorrect. On my local machine (using Python 2 and Python 3), they return the 3, which is correct, as there are 3 keys in the provided dictionary being passed to the function.
c = {'a': 'val1', 'b': 'val2', 'c': 'val3'}
# should return 3
def members(someDic):
count = 0
for key in someDic:
count +=1
return count
# also should return 3
def members(someDic):
count = 0
for key, value in someDic.items():
count +=1
return count
My workaround was to return:
int(count / 3)
in the Challenge workspace.
3 Answers
Robert Richey
Courses Plus Student 16,352 PointsHi Brian,
That is strange! I can, however, point out that the function members
"takes two arguments". Here is how I tend to solve this challenge:
def members(my_dict, my_list):
count = 0
# for each key in my_list:
# if key in my_dict:
# increment count
return count
Brian Hartley
3,115 PointsRobert, you're right, and thanks for the reply. I should have noted that the code I posted was an example of the strange loop behavior, taken from my troubleshooting efforts on my local machine, and not directly from the challenge. I hope I didn't further confuse anyone who has come across this post while dealing with the same issue. The workaround I posted completes the challenge either way.
However, I will also try your if statement tomorrow as well. Perhaps I am going about the loop incorrectly.
Kenneth Love
Treehouse Guest Teacherfor key in my_dict
is always going to only see the keys, that's how looping through a dictionary works.