Skip to content
Advertisement

Pop or Delete a Dictionary item from list

I have this list of dictionary items. I want to delete a specific dictionary entry from the list by comparing it with a dictionary item

items = 
[
{'label': 'Canary Wharf', 'parent': {'label': 'Canada Water', 'parent': None}}, 
{'label': 'Bermondsey', 'parent': {'label': 'Canada Water', 'parent': None}}, 
{'label': 'Surrey Quays', 'parent': {'label': 'Canada Water', 'parent': None}}, 
{'label': 'Rotherhithe', 'parent': {'label': 'Canada Water', 'parent': None}},
{'label': 'Victoria', 'parent': {'label': 'sth', 'parent': None}}, {'label': 'tth', 'parent': {'label': 'sth', 'parent': None}},
{'label': 'stu', 'parent': {'label': 'sth', 'parent': None}}, {'label': 'tth', 'parent': {'label': 'sth', 'parent': None}}
]

I have a variable

to_delete = {'label': 'Surrey Quays', 'parent': {'label': 'Canada Water', 'parent': None}}}

I would like to do,

items.pop(to_delete)
OR
items.delete(to_delete)

To get,

>>>print(items)
[
{'label': 'Canary Wharf', 'parent': {'label': 'Canada Water', 'parent': None}}, {'label': 'Bermondsey', 'parent': {'label': 'Canada Water', 'parent': None}}, 
{'label': 'Victoria', 'parent': {'label': 'sth', 'parent': None}}, {'label': 'tth', 'parent': {'label': 'sth', 'parent': None}},
{'label': 'stu', 'parent': {'label': 'sth', 'parent': None}}, {'label': 'tth', 'parent': {'label': 'sth', 'parent': None}}
]

Advertisement

Answer

It seems that you are trying to delete a tuple of items. Your to_delete is actually a tuple of dictionaries, so to delete them, simply unpack them into separate variables like:

delete1, delete2 = to_delete
items.remove(delete1)
items.remove(delete2)

Alternatively, you can keep one variable and accomplish the same by:

items.remove(to_delete[0])
items.remove(to_delete[1])

Remove method in Python

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement