python基于键值过滤字典列表 [英] python filter list of dictionaries based on key value

查看:35
本文介绍了python基于键值过滤字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典列表,每个字典都有一个(假设)'type'的键,它可以有 'type1''type2' 的值,等.我的目标是将这些词典过滤到相同词典的列表中,但仅限于特定类型"的词典.我想我真的在 list/dictionary 理解上挣扎.

因此示例列表如下所示:

exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]

我有一个键值列表.比如说:

keyValList = ['type2','type3']

预期的结果列表如下所示:

expectedResult = [{'type':'type2'},{'type':'type2'},{'type':'type3'}]

我知道我可以用一组 for 循环来做到这一点.我知道必须有一个更简单的方法.我发现这个问题有很多不同的风格,但没有一个真正符合要求并回答了这个问题.我会尝试回答这个问题……但它们并没有那么令人印象深刻.可能最好让它开放式结束.任何帮助将不胜感激.

解决方案

你可以试试 list comp

<预><代码>>>>exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]>>>keyValList = ['type2','type3']>>>expectedResult = [d for d in exampleSet if d['type'] in keyValList]>>>预期结果[{'type':'type2'}, {'type':'type2'}, {'type':'type3'}]

另一种方法是使用 filter

<预><代码>>>>列表(过滤器(lambda d:d['type'] 在 keyValList,exampleSet))[{'type':'type2'}, {'type':'type2'}, {'type':'type3'}]

I have a list of dictionaries and each dictionary has a key of (let's say) 'type' which can have values of 'type1', 'type2', etc. My goal is to filter out these dictionaries into a list of the same dictionaries but only the ones of a certain "type". I think i'm just really struggling with list/dictionary comprehensions.

so an example list would look like:

exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]

i have a list of key values. lets say for example:

keyValList = ['type2','type3']

where the expected resulting list would look like:

expectedResult = [{'type':'type2'},{'type':'type2'},{'type':'type3'}]

I know i could do this with a set of for loops. I know there has to be a simpler way though. i found a lot of different flavors of this question but none that really fit the bill and answered the question. I would post an attempt at the answer... but they weren't that impressive. probably best to leave it open ended. any assistance would be greatly appreciated.

解决方案

You can try a list comp

>>> exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]
>>> keyValList = ['type2','type3']
>>> expectedResult = [d for d in exampleSet if d['type'] in keyValList]
>>> expectedResult
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]

Another way is by using filter

>>> list(filter(lambda d: d['type'] in keyValList, exampleSet))
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]

这篇关于python基于键值过滤字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆