在值的基础上过滤defaultdict

时间:2016-02-02 23:34:31

标签: python defaultdict

请考虑以下默认词典:

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方法是什么?

2 个答案:

答案 0 :(得分:2)

这将在适当的位置完成。如果您可以制作新词典,可以稍微清理一下。

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}

答案 1 :(得分:1)

我认为这很简单:

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