Remove dictionary from list

前端 未结 7 1216
醉酒成梦
醉酒成梦 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:42

    You could try something along the following lines:

    def destructively_remove_if(predicate, list):
          for k in xrange(len(list)):
              if predicate(list[k]):
                  del list[k]
                  break
          return list
    
      list = [
          { 'id': 1, 'name': 'John' },
          { 'id': 2, 'name': 'Karl' },
          { 'id': 3, 'name': 'Desdemona' } 
      ]
    
      print "Before:", list
      destructively_remove_if(lambda p: p["id"] == 2, list)
      print "After:", list
    

    Unless you build something akin to an index over your data, I don't think that you can do better than doing a brute-force "table scan" over the entire list. If your data is sorted by the key you are using, you might be able to employ the bisect module to find the object you are looking for somewhat faster.

提交回复
热议问题