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

Remove element from list in dictionary

I’m trying to remove element(s) from a list, which is in a dicionary:

data = {"akey": [{"name": "X", "members_id": ["1", "2"]}, {"name": "Y", "members_id": ["1", "3"]}], "bkey": [{"name": "Y", "members_id": ["2", "3"]}]}

print(data)

to_remove = "1"

for key in data:
    for record in data[key]:
        if to_remove in record["members_id"]:
            data[key].remove(record)

print(data)

If to_remove is in record["members_id"], associated item in data[key] should be removed.

In other words, for the example given above, I’m expecting:

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

{"akey": [], "bkey": [{"name": "Y", "members_id": ["2", "3"]}]}

… but I’m getting

{'akey': [{'name': 'Y', 'members_id': ['1', '3']}], 'bkey': [{'name': 'Y', 'members_id': ['2', '3']}]}

Why is the first item in the list the only one getting removed?

>Solution :

As you directly iterate on the list for record in data[key], then of you delete one of the item whils iterating that skips the next one, as the iteration is backed by indices, when you deletenone, everybody after move forward once

Iterate on a copy of the list :

for key in data:
    for record in list(data[key]):
        if to_remove in record["members_id"]:
            data[key].remove(record)

Or keep the valid ones, and reassign them

for key in data:
    data[key] = [x for x in data[key] if to_remove not in x["members_id"]]
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