更快速地过滤字典列表

时间:2017-03-16 03:07:30

标签: python performance dictionary filter

我有一大堆dicts(200,000+),需要根据密钥多次(~11,000)过滤这些dicts。最快的方法是什么?

我正在检索一个dicts(olist)列表,大约225,000个dicts,我正在尝试根据单个键('type')过滤这些dicts。目前,我构建了一个列表中的所有“类型”,然后迭代它,过滤每个“类型”的dicts。我的问题是这个初始'类型'过滤器需要〜。3s,这需要差不多一个小时才能运行。我使用穿线让我降到10多分钟,但我希望接近一半。 Bellow是我的代码的相关片段,是否有更快的方法(更快的过滤器或更有效的算法)?

tLim = threading.BoundedSemaphore(500)
...
olist = _get_co_(h)   ## this returns a list of ~225,000 dictionaries
idlist = list(set([d['type'] for d in olist]))    ## returns list of ~11,000
for i in idlist:
    t = Thread(target=_typeData_, args=(i,olist,cData))
    threads.append(t)

def _typeData_(i,olist,cData):
    tLim.acquire()   
    tList = list(filter(lambda x: x['type'] == i, olist))  ## takes ~0.3s
    do stuff with tList  ## takes ~0.01s

请注意,我看看生成器表达式,但似乎必须存储和回忆结果可能会更糟?我没有尝试过,我不确定如何实现它......

此外,增加信号量并不能提高时间,如果有的话。

1 个答案:

答案 0 :(得分:1)

您可以按类型对字典进行分组,以便以后可以避免使用filter

from collections import defaultdict
id_groups = defaultdict(list)
for dct in olist:
    id_groups[dct['type']].append(dct)

现在您根本不需要过滤,只需迭代此id_groups,您就会得到该类型所有词典的列表:

for i, tList in id_groups.items():
    # the i and tList are identical to your variables in the "_typeData_" function.
    # do something with tList
相关问题