简体   繁体   中英

remove dict from nested list based on key-value condition with python

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?

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

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': []}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM