Home > Blockchain >  Python iteration exclude type not bool, float, int or not NoneType (TypeError: 'NoneType'
Python iteration exclude type not bool, float, int or not NoneType (TypeError: 'NoneType'

Time:10-20

I am trying to iterate a JSON file and its elements. The problem is that error messages are thrown if the value of the first iteration (elements) is of type bool/float/int or NoneType.

This was my try (It works for bool, float and int but throws TypeError: 'NoneType' object is not iterable):

for element in json:
    if type(element) != bool \
                    and type(element) != float \
                    and type(element) != int \
                    and type(element) is not None:
    for value in json[element]:
        print(value)

Is there also a way to shorten the code in Python?

CodePudding user response:

In Python its common to just do it and handle any exceptions.

for element in json:
    try:
        for value in element:
            print(value)
    except TypeError:
        pass

Also, are you sure you want to iterate json[element] or did you mean to iterate over just element in the inner for loop?

  • Related