Remove multiple entries from list python on basis of other list of objects

Question:

I have a scenario I have a array like ['abc' , 'def' , 'cdc'] and a list of object like [{'key': 'abc'} , {'key':'cdc'} ] so now I want to delete only strings from array which I have in key of list of objects .

currently trying this n = [x for x in n if x != 'abc'] but this is for single and don’t seems good way to iterate everytime . so what can be best and effective solution here ?

Asked By: TNN

||

Answers:

Try this:

n= ['abc' , 'def' , 'cdc'] 
d = [{'key': 'abc'} , {'key':'cdc'}]
print([x for x in n if x not in [value['key'] for value in d]])

Output

['def']

[value[‘key’] for value in d] is the extracted keys from the list of objects (or rather… dictionaries in Python lingo)

Answered By: DrCorgi
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.