基于键值的词典python筛选器列表
我有一个字典列表,每个字典都有一个键(比方说)“type”,它的值可以是基于键值的词典python筛选器列表,python,list,python-2.7,dictionary,Python,List,Python 2.7,Dictionary,我有一个字典列表,每个字典都有一个键(比方说)“type”,它的值可以是“type1”,“type2”,等等。我的目标是将这些字典过滤到一个相同字典的列表中,但只能是某个“type”的字典。我想我只是在努力理解list/dictionary 因此,示例列表如下所示: exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}] 我有一个关键值列表。比如说: keyValList = ['t
“type1”
,“type2”
,等等。我的目标是将这些字典过滤到一个相同字典的列表中,但只能是某个“type”的字典。我想我只是在努力理解list/dictionary
因此,示例列表如下所示:
exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]
我有一个关键值列表。比如说:
keyValList = ['type2','type3']
其中,预期的结果列表如下所示:
expectedResult = [{'type':'type2'},{'type':'type2'},{'type':'type3'}]
我知道我可以用一组for循环来实现这一点。我知道必须有一个更简单的方法。我发现这个问题有很多不同的风格,但没有一个真正符合要求并回答了这个问题。我会试着给出答案。。。但他们没有那么令人印象深刻。也许最好是让它开放。如蒙协助,将不胜感激 您可以尝试列表补偿
>>> 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'}]
另一种方法是使用
使用
filter
,或者如果exampleSet
中的词典数量太多,请使用itertools
模块的ifilter
。它将返回一个迭代器,而不是立即用整个列表填充系统内存:
from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
print elem
在Pandas中,这种类型的过滤非常容易,特别是在很多情况下,字典列表作为Pandas数据帧开始时工作得更好
import pandas as pd
exampleSet = [{'type':'type1'}, {'type':'type2'}, {'type':'type2'}, {'type':'type3'}]
keyValList = ['type2', 'type3']
df = pd.DataFrame(my_list)
df[df['type'].isin(keyValList)]
结果:
type
1 type2
2 type2
3 type3
并按照OP的要求以字典形式将其恢复:
expectedResult = df[df['type'].isin(keyValList)].to_dict('records')
# the result will be [{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]
注意:对于Python3,内置的filter()函数返回一个迭代器;itertools.ifilter已被删除。哪一个最快?@DarkSkull我不确定,因为我还没有测试过它。请随意测试,并将答案与您的发现一起发布。:)如果
键不同怎么办?不仅仅是单一的类型
?
expectedResult = df[df['type'].isin(keyValList)].to_dict('records')
# the result will be [{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]