Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (Retired) Dictionaries Teacher Stats

Pete P
Pete P
7,613 Points

Make my 'correct' code better. Is it possible to view instructor's solution?

I'm successfully completing the challenge tasks. However, I'm sure that there sometimes may exist a more efficient, pythonic or just plain better way of doing it. Is it possible to view the instructors answers to the challenges?

As an example, here is my 'Teacher Stats' code. I have a few ideas on how I could shorten the code but I'm failing with implementation...

Thanks for the help!

teachers.py
# The dictionary will be something like:
# {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'],
#  'Kenneth Love': ['Python Basics', 'Python Collections']}
#
# Often, it's a good idea to hold onto a max_count variable.
# Update it when you find a teacher with more classes than
# the current count. Better hold onto the teacher name somewhere
# too!
#
# Your code goes below here.

def most_classes(my_dict):
  max_count = 0
  teacher = ''
  for key in my_dict:
    if len(my_dict[key]) > max_count:
      max_count = len(my_dict[key])
      teacher = key
  return teacher

def num_teachers(my_dict):
  return len(my_dict)

def stats(my_dict):
  my_list = []

  for key in my_dict:
    temp_list = [key, len(my_dict[key])]
    my_list.append(temp_list)
  return my_list

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 67,987 Points

Your stats function is good! The only improvement I see would be to take advantage of the dict.items() method.

By default, when iterating over a dictionary the assumed method is dict.keys(), there is also dict.values() (just the values instead of the keys), and dict.items() which is both the key and the value as a tuple. By using .items() you can save having to look up the teacher's courses again.

temp_list isn't strictly needed, so it can be folded into the append statement.

def stats(my_dict):
    my_list = []

    for key, value in my_dict.items():
        my_list.append([key, len(value)])
    return my_list

If you curious about other questions and solutions on this challenge, you can follow the Teacher Stats link at the top of the page.