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 (2016, retired 2019) Sets Set Math

Deniz Kahriman
Deniz Kahriman
8,538 Points

How can I proceed with the code below? Writing a function to search a set of values within a dict and return their key

Thanks in advance!!!

sets.py
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({set_of_topics}):
    course_list = {}
    for topics in set_of_topics:
            if topics in COURSES.values():
                course_list.add(COURSES.keys())
    final_list = list(course_list)
    return final_list

1 Answer

Stuart Wright
Stuart Wright
41,120 Points

This challenge is easier to solve by looping over the dictionary and checking to see if any of the courses are in the set, rather than the other way around.

The problem with your method is that when you write:

if topics in COURSES.values():
    course_list.add(COURSES.keys())

You are checking if the topic belongs anywhere in the dictionary, and you then add all the keys. When you should only be adding the key that the topic was found in.

Here is my solution using method I've described above:

def covers(set_of_topics):
    course_list = []
    for course, topics in COURSES.items():
        if set_of_topics.intersection(topics):
            course_list.append(course)
    return course_list
Deniz Kahriman
Deniz Kahriman
8,538 Points

Ahhh, it makes sense. Thank you so much!!