List of dictionary concepts - multiple conditions

I have a problem with multiple list conditions:

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 am trying to remove items that satisfy both conditions at the same time.

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

In this case, the element is deleted if at least one condition is met, am I trying to do this in several ways, by any ideas?

Expected Result:

[{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 an element that meets both conditions.

+4
source share
4 answers

Try changing andto or.

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

morgan. : , and or "==" "! =".

+5

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

[{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'}]

, name paul city madrid. , not , False, .

, , , if, .

+5

itemgetter, tuple, :

>>> from operator import itemgetter
>>> name_and_city = itemgetter('name', 'city')
>>> [e for e in listionary if name_and_city(e) != ('paul', 'madrid')]
+2

. namedtuple .

from collections import namedtuple
Profile = namedtuple('Profile', ['city', 'id', 'name'])
listionary = [Profile(*d) for d in listionary]

To improve readability, you can reorganize the condition as a lambda expression (this assumes you are using namedtuple):

removed = lambda ele: \
   ele.name == 'paul' or \
   ele.city == 'madrid'
output = [ele for ele in listionary if not removed(ele)]

I think it is easier to maintain and read, but it may depend on who is looking at it.

+1
source

Source: https://habr.com/ru/post/1624474/


All Articles