基于键值的python过滤器列表 [英] python filter list of dictionaries based on key value
问题描述
'type1'
,'type2'
等等。我的目标是将这些字典过滤掉为相同词典的列表,但只能将某些类型的字典过滤掉。我想我只是真的在努力与列表/字典
理解。 所以一个示例列表将如下所示:
exampleSet = [ {'type':'type1'},{'type':'type2'},{'type':'type2'},{'type':'type3'}
我有一个键值列表。例如:
keyValList = ['type2','type3']
预期结果列表将如下所示:
expectedResult = [{'type':'type2'},{'type':'type2'},{'type':'type3'}]
我知道我可以用一套for循环来做到这一点。我知道有一个更简单的方法。我发现这个问题有很多不同的口味,但没有一个真的适合这个法案,并回答了这个问题。我会在答案中发表一个尝试,但他们并没有那么令人印象深刻。可能最好让它开放。任何协助将不胜感激。
您可以尝试列表comp
code>>>> example ='type2'},{'type':'type2'},{'type':'type3'}]
>> ;> keyValList = ['type2','type3']
>>> expectedResult = [d for example in exampleSet if d ['type'] in keyValList]
>>>> expectedResult
[{'type':'type2'},{'type':'type2'},{'type':'type3'}]
另一种方法是使用 过滤器
>>>列表(key)中的filter(lambda d:d ['type'])
[{'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屋!