Remove dictionary from list

前端 未结 7 1195
醉酒成梦
醉酒成梦 2020-12-04 14:32

If I have a list of dictionaries, say:

[{\'id\': 1, \'name\': \'paul\'},
 {\'id\': 2, \'name\': \'john\'}]

and I would like to remove the d

相关标签:
7条回答
  • 2020-12-04 15:00

    Here's a way to do it with a list comprehension (assuming you name your list 'foo'):

    [x for x in foo if not (2 == x.get('id'))]
    

    Substitute 'john' == x.get('name') or whatever as appropriate.

    filter also works:

    foo.filter(lambda x: x.get('id')!=2, foo)

    And if you want a generator you can use itertools:

    itertools.ifilter(lambda x: x.get('id')!=2, foo)

    However, as of Python 3, filter will return an iterator anyway, so the list comprehension is really the best choice, as Alex suggested.

    0 讨论(0)
提交回复
热议问题