Search code examples
pythondefaultdict

Filtering defaultdict on the base of value


Consider following default dict:

data = defaultdict(list)
data['key1'] = [{'check': '', 'sth1_1':'k1', 'sth1_2':'k2'}]
data['key2'] = [{'check': '0', 'sth2_1':'k3'}, {'check': 'asd', 'sth2_2':'k4'}, {'check':'1', 'sth2_3':'k5'}]

and so on..

I would like to filer out from data dictionaries (from data.values()) which value 'check' != '1'

For given input above i'd expect:

defaultdict(<type 'list'>, {'key2': [{'sth2_3': 'k5', 'check': '1'}])

So far i've got:

for k, v in data.items():
    print "k, v: ", k, v
    v[:] = [d for d in v if d.get('check') == '1']

But it gives me output with unwanted 'key1': [] :

defaultdict(<type 'list'>, {'key2': [{'sth2_3': 'k5', 'check': '1'}], 'key1': []})

What would be the best pythonic way to solve that?


Solution

  • I think this is simple enough:

    for k,v in data.items():
        filtered_vals = list(filter(lambda i: i['check'] == '1', v)
        if len(filtered_vals):
            data[k] = filtered_vals
        else:
            del data[k]
    

    or if you're insane:

    data = {k:v for k,v in { k:list(filter(lambda i: i['check'] == '1' ,v)) for k, v in data.items()}.items() if len(v)}