根据值过滤 defaultdict

Filtering defaultdict on the base of value

考虑以下默认字典:

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'}]

等等..

我想从 data 字典(来自 data.values())中找出值 'check' != '1'

对于上面的给定输入,我期望:

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

到目前为止我有:

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

但它给了我不需要的输出 'key1': [] :

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

解决这个问题的最佳 pythonic 方法是什么?

这就到位了。如果您可以制作新词典,它可以稍微清理一下。

for key in data.keys():
    new_list = []
    for val in data[key]:
        if val['check'] == '1':
            new_list += [val]
    if new_list:
        data[key] = new_list
    else:
        del data[key]

如果你真的想使用(嵌套的)理解,这也行得通:

d = {}
d = {key: [inner_dict for inner_dict in list_of_dicts if inner_dict['check'] == '1'] for key, list_of_dicts in data.iteritems()}
d = {key: val for key,val in d.iteritems() if val}

我觉得这很简单:

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]

或者如果你疯了:

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)}