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 trialWilly Meier
6,926 PointsI tried almost same code on workspace and it works, but I still get keyerror 3 related to my_dict[x].
Code I used on workspace and works: def members(my_dict, my_list): x = 3 z = 0 while x: for item in my_list: if item == my_dict[x]: z += 1 x -= 1 print(z)
my_list = ['apples', 'coconuts', 'grapes', 'strawberries'] my_dict = {1 : 'apples', 2 : 'bananas', 3 : 'coconuts'}
members(my_dict, my_list)
# 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):
x = 3
z = 0
while x:
for item in my_list:
if item == my_dict[x]:
z += 1
x -= 1
return z
2 Answers
Maciej Walczak
5,042 PointsI redid your code into this since i think you dont need a while loop. You just need to go through the list and update answer variable.
def member(my_dict, my_list):
answer = 0
for item in my_list:
if item in my_dict: #you need to check if item is in my_dict not if item is [x] index in my_dict
answer += 1
return answer
Willy Meier
6,926 PointsHi Maciej, Thanks! Good to know that I can compare items in list and in a dictionary directly. Willy
Haider Ali
Python Development Techdegree Graduate 24,728 PointsHaider Ali
Python Development Techdegree Graduate 24,728 PointsHi Maciej, I felt that your comment was a very good solution so I have changed it to an answer. Well done :).