Prajoth Prajoth - 1 year ago 35
Python Question

Python - Filter list of dictionaries based on if key value contains all items in another list

I have a list of dictionaries that looks like this, but with around 500 items:

listOfDicts = [{'ID': 1, 'abc': {'123': 'foo'}}, ... {'ID': 7, 'abc': {'123':'foo','456': 'bar'}}]

sampleFilterList = ['123', '456']


I am trying to filter the listOfDicts for all the results where all the values in the sampleFilterList are in the key 'abc'

The result should be a list:

[{'ID': 7, 'abc': {'123':'foo','456': 'bar'}}, ...]


I tried
[i for i in listOfDicts if a for a in sampleFilterList in i['abc']]
, but I am getting an
UnboundLocalError: local variable 'a' referenced before assignment

DYZ DYZ
Answer Source

First, convert your second list to a set for more efficient comparisons:

sampleFilterSet = set(sampleFilterList)

Now, compare the 'abc' keys for each list item to the aforesaid set:

[item for item in listOfDicts if not (sampleFilterSet - item['abc'].keys())]    
#[{'ID': 7, 'abc': {'123': 'foo', '456': 'bar'}}]

This is the fastest solution. A more Pythonic (but somewhat slower) solution is to use filter():

list(filter(lambda item: not (sampleFilterSet - item['abc'].keys()), listOfDicts))
#[{'ID': 7, 'abc': {'123': 'foo', '456': 'bar'}}]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download