Remove dictionary from list

前端 未结 7 1228
醉酒成梦
醉酒成梦 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 14:38

    Supposed your python version is 3.6 or greater, and that you don't need the deleted item this would be less expensive...

    If the dictionaries in the list are unique :

    for i in range(len(dicts)):
        if dicts[i].get('id') == 2:
            del dicts[i]
            break
    

    If you want to remove all matched items :

    for i in range(len(dicts)):
        if dicts[i].get('id') == 2:
            del dicts[i]
    

    You can also to this to be sure getting id key won't raise keyerror regardless the python version

    if dicts[i].get('id', None) == 2

提交回复
热议问题