Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list of dictionaries comprehension - multiple conditions

I have a problem with multiple conditions with list:

listionary = [{u'city': u'paris', u'id': u'1', u'name': u'paul'},
              {u'city': u'madrid', u'id': u'2', u'name': u'paul'},
              {u'city': u'berlin', u'id': u'3', u'name': u'tom'},
              {u'city': u'madrid', u'id': u'4', u'name': u'tom'}]

I try to delete items that meet both conditions simultaneously.

[elem for elem in listionary if (elem.get('name')!='paul' and elem.get('city')!='madrid')]

In this case element is removed if meet at least one condition, I try to do it in several ways, any ideas?

Expected output:

[{u'city': u'paris', u'id': u'1', u'name': u'paul'}
{u'city': u'berlin', u'id': u'3', u'name': u'tom'}
{u'city': u'madrid', u'id': u'4', u'name': u'tom'}]

I would like to remove element which meet both conditions.

like image 809
causeyo Avatar asked Dec 11 '22 18:12

causeyo


2 Answers

Try changing the and to or.

[elem for elem in listionary if (elem.get('name')!='paul' or elem.get('city')!='madrid')]

Remember de morgan's laws. Informally: when you negate a boolean expression, you have to switch and with or in addition to switching "==" with "!=".

like image 198
Kevin Avatar answered Dec 31 '22 02:12

Kevin


Your condition should have been like this

[e for e in data if not (e.get('name') == 'paul' and e.get('city') == 'madrid')]

Output

[{u'city': u'paris', u'id': u'1', u'name': u'paul'},
 {u'city': u'berlin', u'id': u'3', u'name': u'tom'},
 {u'city': u'madrid', u'id': u'4', u'name': u'tom'}]

This checks if the current element's name is paul and city is madrid. If both the conditions are satisfied, the not outside will flip it, so you will get False and the item will be omitted.

Basically you are checking if the current item is the one which you don't want and make the if condition fail if it is.

like image 35
thefourtheye Avatar answered Dec 31 '22 04:12

thefourtheye