python基于键值过滤字典列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29051573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python filter list of dictionaries based on key value
提问by m25
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.
我有一个字典列表和每个字典的key(比方说)“型”,这可以有值'type1'
,'type2'
等我的目标是过滤掉这些字典到同一个字典列表,但只有一个的那些某种“类型”。我想我只是真的在list/dictionary
理解上挣扎。
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.
我知道我可以用一组 for 循环来做到这一点。我知道必须有一个更简单的方法。我发现这个问题有很多不同的风格,但没有一个真正符合要求并回答了这个问题。我会尝试回答这个问题……但它们并没有那么令人印象深刻。可能最好让它开放式结束。任何帮助将不胜感激。
采纳答案by Bhargav Rao
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
另一种方法是使用 filter
>>> list(filter(lambda d: d['type'] in keyValList, exampleSet))
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]
回答by Saksham Varma
Use filter
, or if the number of dictionaries in exampleSet
is too high, use ifilter
of the itertools
module. It would return an iterator, instead of filling up your system's memory with the entire list at once:
使用filter
,或者如果在字典的数量exampleSet
太高,使用ifilter
的的itertools
模块。它会返回一个迭代器,而不是一次用整个列表填满系统的内存:
from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
print elem