Nan values in a list of dictionaries

Viewed 575

Am Trying to print if there is a nan value in a list of dictionaries but failed to do so.

data = [{'A' : 2, 'B' : 'ssss'}, {'A' : 3, 'B' : 'xxx'}, {'A' :nan, 'B' : 'ssss'}]

Code :

for x in data:
    if (x['A']== 2):
        print('two')
    elif (x['A']== np.nan)
        print('null')
    else:
        print('nothing')
3 Answers

You can obtain the dictionary's values using dict.values, in this case we can just map with this method, and check if any values in the returned generator are unequal to themselves, meaning that they are NaN:

from itertools import chain
data = [{'A' : 2, 'B' : 'ssss'}, {'A' : 3, 'B' : 'xxx'}, 
        {'A' :float('nan'), 'B' : 'ssss'}]

any(i!=i for i in chain.from_iterable(map(dict.values, data)))
# True

Or following the logic in your code:

for x in data:
    if (x['A']== 2):
        print('two')
    elif (x['A']!= x['A']):
        print('null')
    else:
        print('nothing')

You can use if (x['A'] is np.nan) instead of ==

Related