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

m25*_*m25 46 python dictionary list python-2.7

我有一个字典列表和每个字典里的(比方说)"型",这可以有值的键'type1','type2'等我的目标是将这些字典筛选出到相同的词典,但只有一个的那些名单某种"类型".我想我只是在list/dictionary理解中苦苦挣扎.

所以示例列表看起来像:

exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]
Run Code Online (Sandbox Code Playgroud)

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

keyValList = ['type2','type3']
Run Code Online (Sandbox Code Playgroud)

预期结果列表的位置如下:

expectedResult = [{'type':'type2'},{'type':'type2'},{'type':'type3'}]
Run Code Online (Sandbox Code Playgroud)

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

Bha*_*Rao 85

你可以尝试列表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'}]
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用 filter

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

  • 哪个最快? (2认同)
  • 如果“密钥”不同怎么办?不只是单一的“类型”? (2认同)

kov*_*awa 40

尝试了这篇文章中的一些答案,我测试了每个答案的性能。

\n

正如我最初的猜测,到目前为止,列表理解速度更快filterandlist方法是第二,而 the是第三。pandas

\n
\n

定义的变量:

\n
\n
import pandas as pd\n\nexampleSet = [{\'type\': \'type\' + str(number)} for number in range(0, 1_000_000)]\n\nkeyValList = [\'type21\', \'type950000\']\n
Run Code Online (Sandbox Code Playgroud)\n
\n
\n

第一 -list comprehension

\n
%%timeit\nexpectedResult = [d for d in exampleSet if d[\'type\'] in keyValList]\n
Run Code Online (Sandbox Code Playgroud)\n
\n

每个循环 60.7 ms \xc2\xb1 188 \xc2\xb5s(平均 7 次运行的 \xc2\xb1 标准偏差,每次 10 个循环)

\n
\n

第二个 -filterlist

\n
%%timeit\nexpectedResult = list(filter(lambda d: d[\'type\'] in keyValList, exampleSet))\n
Run Code Online (Sandbox Code Playgroud)\n
\n

每个循环 94 ms \xc2\xb1 328 \xc2\xb5s(意味着 7 次运行的 \xc2\xb1 标准偏差,每次 10 个循环)

\n
\n

第三-pandas

\n
%%timeit\ndf = pd.DataFrame(exampleSet)\nexpectedResult = df[df[\'type\'].isin(keyValList)].to_dict(\'records\')\n
Run Code Online (Sandbox Code Playgroud)\n
\n

336 ms \xc2\xb1 每个循环 1.84 ms(平均 \xc2\xb1 标准偏差 7 次运行,每次 1 次循环)

\n
\n
\n

顺便说一句,使用pandasa 来处理 adict并不是一个好主意,因为 apandas.DataFrame基本上会消耗更多的内存dict,并且如果您最终不打算使用数据帧,那么它的效率就会很低。

\n


Sak*_*rma 15

使用filter,或者如果字典数exampleSet太高,则使用ifilteritertools模块.它将返回一个迭代器,而不是立即用整个列表填充系统的内存:

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

  • 注意:对于Python3,内置的filter()函数返回一个迭代器;itertools.ifilter已删除。 (3认同)