python - 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 on..

i filer out data dictionaries (from data.values()) 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 d in v if d.get('check') == '1'] 

but gives me output unwanted 'key1': [] :

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

what best pythonic way solve that?

i think 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 k,v in { k:list(filter(lambda i: i['check'] == '1' ,v)) k, v in data.items()}.items() if len(v)} 

Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -