Jake Lazzari
Jake Lazzari

Reputation: 3

How to delete a dictionary in a list in python?

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}]

Upvotes: 0

Views: 81

Answers (2)

Siddhant Shrivastav
Siddhant Shrivastav

Reputation: 309

You can try this:

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

Upvotes: 0

pissall
pissall

Reputation: 7399

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]

Upvotes: 1

Related Questions