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 (Retired) Dictionaries Dictionary Iteration

Stephanie Marson
Stephanie Marson
7,627 Points

Python Code works in Command Prompt but not Treehouse

I am working on Stage 3 dictionaries > Teacher Stats. I made it to task 3 before i was given the error message : task 1 is no longer correct. I went back to task 1 and resubmitted the code. Now i am receiving the message: most_classes()` returned Kenneth Love, expected 'Jason Seifer'. However, when i run this code in the command prompt, i receive 'Jason Seifer.' Why does it work in my command prompt and not treehouse?

My code:

teachers = {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'],'Kenneth Love': ['Python Basics', 'Python Collections']} class_count = 0 max_count = 0 max_teacher = ()

def most_classes(x): for key in teachers: class_count = len(teachers[key]) if class_count > max_count: max_teacher = key return max_teacher

most_classes(teachers)

1 Answer

Mikael Enarsson
Mikael Enarsson
7,056 Points

You have to reassign max_count to the value of class_count. Also, I had to move the variables into the function. Not sure why, but having variables used locally locally is better practice anyway:

def most_classes(teachers):
  max_count = 0 
  max_teacher = ''
  for key in teachers:
    class_count = len(teachers[key]) 
    if class_count > max_count:
      max_teacher = key                   #You have to reassign max_count to have the current
      max_count = class_count             #class count here
  return max_teacher

As to why you got the correct answer in the prompt, it's probably because dicts are unsorted, and the function just happened to access 'Jason Seifer' first.

Edit: Oh, and you should make it so the function has an argument for a dict ^^