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 trialAlejandro Byrne
2,562 PointsHow to loop for item in an item
Hi, I think I have the challenge down, just not sure how to do a for loop for an item in an item - probably did it wrong. Any help? Thanks.
COURSES = {
"Python Basics": {"Python", "functions", "variables",
"booleans", "integers", "floats",
"arrays", "strings", "exceptions",
"conditions", "input", "loops"},
"Java Basics": {"Java", "strings", "variables",
"input", "exceptions", "integers",
"booleans", "loops"},
"PHP Basics": {"PHP", "variables", "conditions",
"integers", "floats", "strings",
"booleans", "HTML"},
"Ruby Basics": {"Ruby", "strings", "floats",
"integers", "conditions",
"functions", "input"}
}
def covers(topics):
result = []
for item in item in COURSES:
if topics in item:
result.append(item)
return result
1 Answer
Jeff Wilton
16,646 PointsYou are on the right track! When you iterating through a loop, think of it as 'for item in collection', not 'for item in item'. In this example, it is actually 'for item in collection in collection'.
When doing list comprehension on a Set for example, you can simply say 'for item in collection', but since we want to use both the key and the value of the inner dictionary, we want this syntax: 'for key, value in dictionary.items()'.
Here is how the corresponding code would look:
def covers(topics):
result = []
for topic in topics:
for course_key, course in COURSES.items():
if topic in course:
result.append(course_key)
return result
Alejandro Byrne
2,562 PointsAlejandro Byrne
2,562 PointsAhhhh... yes, forgot to add the .items() for dictionaries. And didn't think really know about the way of checking in a loop, thanks!