how to remove item not match in list of object list

Question:

Here is my list, it’s list of object and inside object there is list:
please rev

[
    {
        "id": 1,
        "test": [
            {
                "id__": 1
            },
            {

                "id__": 1
            },
            {

                "id__": 1
            },
            {
                "id__": 2
            }
        ]
    },
    {
        "id": 2,
        "test": [
            {

                "id__": 1
            },
            {

                "id__": 1
            },
            {

                "id__": 1
            },
            {
                "id__": 2
            }
        ]
    }
]

I want to remove matched id with one in objecso it can be like this :

[
    {
        "id": 1,
        "test": [
            {
                "id__": 1
            },
            {

                "id__": 1
            },
            {

                "id__": 1
            }
        ]
    },
    {
        "id": 2,
        "test": [

            {
                "id__": 2
            }
        ]
    }
]

Here is what I try:
and notice that is final is the list mentioned above

for i in final:
    for j in i["test"]:
        if j['id__'] == i["id"]:
            i.pop()

can I use some help of you kind guys, I tried with remove attribute in list, and still no result satisfied.

Asked By: test new jiras

||

Answers:

This is probably what you want:

filtered_result = []
for i in a:
    lst_id = i["id"]
    lst_to_compare = i["test"]
    filtered_inner_list = [item for item in lst_to_compare if item["id__"] == lst_id]
    filtered_result.append({"id": lst_id, "test": filtered_inner_list})

print(filtered_result)
Answered By: Ahsanul Haque

Here’s how I would solve this problem, hope it helps. The problem with your solution was that you were trying to eliminate the item of a list which you were looping over, so the whole iteration was faulty.

ind_list = list()
for key in my_list:
    id_num = key['id']
    for item in key['test']:
        if item['id__'] != id_num:
            ind_list.append(key['test'].index(item))
    for i in ind_list:
        key['test'].pop(i)
    ind_list.clear()
print(my_list)
Answered By: Pouya Mohammadi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.