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')
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With