jeudi 17 décembre 2020

A condition for checking if a field is 'None' is not working as expected

So I'm running a basic loop that's iterating through a list of items containing a dictionary and I'm filtering the list on the basis of if the selected key !=" " or None. However, the !=" " part seems to be working but the None check is not working.

Here's what I'm trying to say in code form

data = [{'Field': 'somevalue', 'Anotherfield': 'somevalue'}, {'Field': 'somevalue', 'Anotherfield': ''}, {'Field': 'somevalue', 'Anotherfield': None}}
datanew = []

for items in data:
  if items['Anotherfield']!= '' or items['Anotherfield'] is None:
    datanew.append(items)

What I should be getting is datanew = [{'Field': 'somevalue', 'Anotherfield': 'somevalue'}] vs what I'm getting datanew = [{'Field': 'somevalue', 'Anotherfield': 'somevalue'}, {'Field': 'somevalue', 'Anotherfield': None}]

I think it's just a simple mistake in the if condition somehow, but I've gone over it a lot of times now and haven't been able to figure it out yet. What am I doing wrong here?

Thank you.

Aucun commentaire:

Enregistrer un commentaire