python过滤基于键值的词典列表

时间:2015-03-14 16:52:44

标签: python list python-2.7 dictionary

我有一个字典列表,每个字典都有一个键(让我们说)'类型'它的值可以是'type1''type2'等。我的目标是将这些词典过滤成相同词典的列表,但只过滤某些词典的类型"。我认为我真的很挣list/dictionary理解。

所以示例列表如下:

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

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

keyValList = ['type2','type3']

预期结果列表如下所示:

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

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

3 个答案:

答案 0 :(得分:71)

您可以尝试列表补充

>>> 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

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

答案 1 :(得分:15)

使用filter,或者如果exampleSet中的词典数量过高,请使用ifilter模块的itertools。它将返回一个迭代器,而不是立即用整个列表填充系统的内存:

from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
    print elem

答案 2 :(得分:-2)

这种类型的过滤在 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'}]