Skip to content
Advertisement

TypeError: can’t convert type ‘NoneType’ to numerator/denominator

Here I try to calculate mean value based on the data in two list of dicts. Although I used same code before, I keep getting error. Is there any solution?

JavaScript

Too see csv files: https://repl.it/@rmakakgn/SVE2

Advertisement

Answer

.get method of dict return None if given key does not exist and statistics.mean fail due to that, consider that

JavaScript

result in:

JavaScript

You need to remove Nones before feeding into statistics.mean, which you can do using list comprehension:

JavaScript

or filter:

JavaScript

(both snippets above code will print 2)

In this particular case, you might get filter effect by replacing:

JavaScript

with:

JavaScript

though as with most python built-in and standard library functions accepting list as sole argument, you might decide to not build list but feed created generator directly i.e.

JavaScript

For further discussion see PEP 202 xor PEP 289.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement