Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading