0
a = [
    {
        "id" : 15,
        "name" : "abc"
    },
    {
        "id" : 16,
        "name" : "xyz"
    },
    {
        "id" : 17,
        "name" : "pqr"
    }
]

b = [15,17]

I have two lists as above, I want to remove the object from list a if its id is not present in list b. Any help, how to do that?

Output List:

[
    {
        "id" : 15,
        "name" : "abc"
    },
    {
        "id" : 17,
        "name" : "pqr"
    }
]
2

3 Answers 3

6

Iterate in reverse gear for efficient, in-place deletion. Convert b into a set for constant time lookup.

c = set(b)    
for i in reversed(range(len(a))):  # thanks to @juanpa.arrivillaga for this bit 
    if a[i]['id'] not in c:
        del a[i]

Otherwise, use a list comprehension and create it again:

a = [i for i in a if i['id'] in c]

print(a)
[{'id': 15, 'name': 'abc'}, {'id': 17, 'name': 'pqr'}]
Sign up to request clarification or add additional context in comments.

2 Comments

I've come to prefer reversed(range(len(a))) instead of range(len(a) - 1, -1, -1)
@juanpa.arrivillaga Will commit that to memory! Very nifty.
0

use list comprehention hence:

[i for i in a if i['id']!=b[0] and i['name']!=b[1]]

1 Comment

I think your answer is wrong because b[0], b[1], and i['name'] are not relevant, and OP wants to keep those items whose ids are in b. So [i for i in a if i['id'] in b] might be what you are trying to say.
0

You can use list comprehension as follows:

a = [
     {
        "id" : 15,
        "name" : "abc"
    },
    {
        "id" : 16,
        "name" : "xyz"
    },
    {
        "id" : 17,
        "name" : "pqr"
    }]

b = [15, 17]

print [a[_] for _ in xrange(len(a)) if a[_]["id"] in b]

output:

[{'id': 15, 'name': 'abc'}, {'id': 17, 'name': 'pqr'}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.