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

Jade Newbury
PRO
Jade Newbury
Pro Student 10,196 Points

This method won't work with None types - can anyone please explain?

The code I used for the num_courses challenge below will work on strings and integers, however, when I tested in a workspace and included a None as one of the values (spanish_inqisition=None), then I got an error: TypeError: object of type 'NoneType' has no len()

So how would I be able to counter this error for dictionaries that contain None types and still be able to count the total values?

teachers.py
# 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):
    return(len(dict.keys())) #number of teachers

def num_courses(dict):
    total = 0
    for x in dict.values():
        total += len(x)
    return total

1 Answer

Steven Parker
Steven Parker
171,228 Points

This would not likely be something you'd need in a practical situation. In this example, if a teacher had no courses, their key would either be omitted entirely from the dictionary, or the associated value would be an empty list instead of "None". Either way, the code would function as expected.

In the unlikely event that a dictionary might legitimately contain a mix of lists and "None", you would just need to specifically test for "None" before performing any operation that assumes the value contains a list.

Jade Newbury
Jade Newbury
Pro Student 10,196 Points

Okay, I see, so I'd have to test the dictionary for any None values and then maybe remove them before I can perform any such operations like the one in the challenge(totaling the values)?

Steven Parker
Steven Parker
171,228 Points

You might not want to alter the dictionary, but by detecting the "None" in the loop, you can handle it differently (perhaps just ignoring it) to avoid the error.

Jade Newbury
Jade Newbury
Pro Student 10,196 Points

Yes, I just wanted to know what the best practice would be in this scenario. Thanks for your answer...iut was really helpful :)

Steven Parker
Steven Parker
171,228 Points

Jade Newbury — Glad to help. You can mark a question solved by choosing a "best answer".
And happy coding!