0

I am just looking for help to delete a specific dictionary in a list with a specific stipulation without using the index number.

For example, how would I remove supplier with supplier_id=103 in the following

suppliers = [
{"contact_firstname": "Jason", 
 "supplier_id": 101},
{"contact_firstname": "Paul", 
 "supplier_id": 102},
{"contact_firstname": "Mark", 
 "supplier_id": 103}]
  • Get the index of the element you want to remove, then use `suppliers.pop(index)` – Barmar Mar 23 '20 at 05:21
  • I'm trying to do it without knowing the index number. I understand you can use this but was looking a way to do it without – Jake Lazzari Mar 23 '20 at 05:22
  • You can find the index number with a simple loop. See https://stackoverflow.com/questions/4391697/find-the-index-of-a-dict-within-a-list-by-matching-the-dicts-value – Barmar Mar 23 '20 at 13:40

2 Answers2

1

You can write it like this:

supplier_list2 = [x for x in suppliers if x["supplier_id"] != 103]

It will remove all entries with supplier_id 103. If you want to exclude a list of ID's:

excluded = [102, 103]
supplier_list2 = [x for x in suppliers if x["supplier_id"] not in excluded]
pissall
  • 7,109
  • 2
  • 25
  • 45
0

You can try this:

suppliers[:] = [d for d in suppliers if d.get('supplier_id') != 103]