Home > Back-end >  Filter an array object by a list in Python
Filter an array object by a list in Python

Time:07-04

What is the easiest way to do the following task ? Many thanks

obj = [ 
    { 'uniqueID' : "B111222", "Fees" : 111}, 
    { 'uniqueID' : "B222111", "Fees" : 222}, 
    { 'uniqueID' : "B333111", "Fees" : 333}
]


unwanted = [ "B111222", "B222111"]

Outcomes

>>>> [{'uniqueID': 'B333111', 'Fees': 333}]

CodePudding user response:

A comprehension approach will work:

obj = [ 
    { 'uniqueID' : "B111222", "Fees" : 111}, 
    { 'uniqueID' : "B222111", "Fees" : 222}, 
    { 'uniqueID' : "B333111", "Fees" : 333}
]

unwanted = [ "B111222", "B222111"]

filtered = [d for d in obj if d['uniqueID'] not in unwanted]

print(filtered)

[{'uniqueID': 'B333111', 'Fees': 333}]

If the dictionaries in obj are not guaranteed to have a uniqueID, then some additional error checking will be necessary.

filtered = [d for d in obj if 'uniqueID' in d.keys() 
            and d['uniqueID'] not in unwanted]
  • Related