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 trialIdris Abdulwahab
Courses Plus Student 2,961 PointsGet Key with maximum value in dictionary
My code is attached.
The problem is with the most_courses function. The code challenge was to return the name of the teacher with the maximum number of courses, which translates to the Key with the maximum value in the dictionary.
What I tried to do was to iterate through the values so that len(value) gives me number of courses in the value if in a list, while I get a figure of 1 if the value only holds a string.
But somehow, I got the whole thing confused when I try to obtain the max value.
Please help.
Thanks.
# The dictionary will look something like:
# {'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],
# 'Kenneth Love': ['Python Basics', 'Python Collections']}
#
# Each key will be a Teacher and the value will be a list of courses.
#
# Your code goes below here.
def num_teachers(dict):
num = len(dict.keys())
return (num)
def num_courses(dict):
count = 0
for key, value in dict.items():
if type(value) is list:
count += len(value)
else:
count += 1
return (count)
def courses(dict):
good = []
for key, value in dict.items():
if type(value) is list:
for item in value:
good.append(item)
else:
good.append(value)
return (good)
def most_courses(dict):
count = 0
for v in dict.values():
if type(v) is list:
count = len(v)
else:
count = 1
maxcount = max((count) for v in dict.values())
for k, v in dict.items():
if count == maxcount:
return (k)
1 Answer
Andrey Misikhin
16,529 Pointsdef most_courses(dict):
count = 0
name = ''
for teacher, course in dict.items():
if type(course) is list and len(course) >= count:
name = teacher
elif count == 0:
name = teacher
return name