Home > front end >  remove dict from nested list based on key-value condition with python
remove dict from nested list based on key-value condition with python

Time:03-25

Im trying to remove a dict from a list only if the condition is met. there are with key decision = "Remove" in the nested dict, I wish to keep only the elements which with key decision = "keep".

For example,

 mylist = [
        {
            "id": 1,
            "Note": [
                {
                    "xx": 259,
                    "yy": 1,
                    "decision": "Remove"
                },
                {
                    "xx": 260,
                    "yy": 2,
                    "decision": "keep"
                }
            ]
        },
        {
            "id": 1,
            "Note": [
                {
                    "xx": 303,
                    "yy": 2,
                    "channels": "keep"
                }
            ]
        }
    ]

output:

[
    {
        "id": 1,
        "Note": [
            {
                "xx": 260,
                "yy": 2,
                "decision": "keep"
            }
        ]
    },
    {
        "id": 1,
        "Note": [
            {
                "xx": 303,
                "yy": 2,
                "channels": "keep"
            }
        ]
    }
]

My solution: This doesn't seem right.

 for d in mylist:
    for k,v in enumerate(d['Note']):
        if v["decision"] == "Remove":
            del d[k]

Any help please?

CodePudding user response:

Very similar to @sushanth's answer. The difference is, it's agnostic about the other key-value pairs in the dicts and only drops the dicts where decision is "Remove":

for d in mylist:
    d['Note'] = [inner for inner in d['Note'] if inner.get('decision')!='Remove']

Output:

[{'id': 1, 'Note': [{'xx': 260, 'yy': 2, 'decision': 'keep'}]},
 {'id': 1, 'Note': [{'xx': 303, 'yy': 2, 'channels': 'keep'}]}]

CodePudding user response:

try using list comprehension

print(
    [
        {
            "id": i['id'],
            "Note": [j for j in i['Note'] if j.get('decision', '') == 'keep']
        }
        for i in mylist
    ]
)

[{'id': 1, 'Note': [{'xx': 260, 'yy': 2, 'decision': 'keep'}]}, {'id': 1, 'Note': []}]
  • Related