Python Python Collections (2016, retired 2019) Dictionaries Teacher Stats

Code Challenge Error

When I ran this code in Workspaces, it gave the desired output(you can try it if you don't believe me). When I pressed the "check work" button(using the same code), it threw a TypeError: unsupported operand type "+" for int and list.

Thank you for your attention!

teachers.py
def num_teachers(treehouse_dict = {}):
    return len(treehouse_dict)


def num_courses(treehouse_dict = {}):
    total_val = 0
    for key, value in treehouse_dict.items():
        total_val = total_val + value
    return total_val

4 Answers

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 47,519 Points

value is still a list and can't be added to an integer. I was attempting to show that. The task asks for the total number of courses for all teachers. To get that you will have to count the items in each list. You have the loop set up but aren't counting items. The following will do so:

def num_courses(treehouse_dict = {}):
    total_val = 0
    for key, value in treehouse_dict.items():
        total_val = total_val + len(value)
    return total_val

and passes the challenge.

If you don't agree can you post your workspace as a snapshot and the steps you took to test?

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 47,519 Points

I tried your code in a workspace and received the same error as the challenge. The following:

d = {'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],
  'Kenneth Love': ['Python Basics', 'Python Collections']}

def num_courses(treehouse_dict = {}):
    total_val = 0
    for key, value in treehouse_dict.items():
        if isinstance(value,list):
            print("I am a list")  

        total_val = total_val + value
    return total_val

print(num_courses(d))  

results with:

I am a list                                                                              
Traceback (most recent call last):                                                       
  File "a.py", line 13, in <module>                                                      
    print(num_courses(d))                                                                
  File "a.py", line 10, in num_courses                                                   
    total_val = total_val + value                                                        
TypeError: unsupported operand type(s) for +: 'int' and 'list'  

Since value is a list you should use the len() function here as well to get an item count

the code you ran isn't my code. Here is my code:

def num_courses(treehouse_dict = {}): total_val = 0 for key, value in treehouse_dict.items(): total_val = total_val + value return total_val

That is my code