gpt4 book ai didi

python - 根据值过滤 defaultdict

转载 作者:太空宇宙 更新时间:2023-11-04 00:55:50 32 4
gpt4 key购买 nike

考虑以下默认字典:

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}

关于python - 根据值过滤 defaultdict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35165864/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com