Skip to main content
 首页 » 编程设计

Python:从字典中删除大量键的最快策略

2024年11月01日8zhwl

据我所知,Python 字典是一个 HashTable,如果表的大小超过当前表的最大大小 (Objects\dictnotes.txt) 的 2/3,它会调整大小。

我需要删除很多字典项(数千个),例如,一个小时一次,基于简单的标准 - 如果键 <= guard_condition。

我知道关于创建新字典和在迭代时调整字典大小的字典理解。

# dict comprehension 
new_d = {key: value for key, value in d.iteritems() if key >= guard_condition } 
 
# resize while iterating 
for key in d: 
    if key < guard_condition: 
        del d[key] 

还有其他方法可以达到这个目的吗? 哪个更快?

请您参考如下方法:

这取决于您的字典大小以及您必须删除的元素数量:如果您删除的字典键少于 80%,则“迭代时调整大小”比“字典理解”更快。如果您删除超过 80% 的字典键,那么“字典理解”会更快。用这段代码自己试试

import cProfile, pstats, StringIO 
pr = cProfile.Profile() 
pr.enable() 
 
guard_condition = int(raw_input("Enter guard_condition: ")) 
 
d = {item: item for item in xrange(10000000)}; 
 
new_d = {key: value for key, value in d.iteritems() if key >= guard_condition } 
 
def del_iter(d, guard_condition): 
    for key in d.keys(): 
        if key < guard_condition: 
            del d[key] 
 
del_iter(d, guard_condition) 
 
pr.disable() 
s = StringIO.StringIO() 
sortby = 'cumulative' 
ps = pstats.Stats(pr, stream=s).sort_stats(sortby) 
ps.print_stats() 
print s.getvalue() 

对于 guard_condition = 7000000,输出为

ncalls  tottime  percall  cumtime  percall filename:lineno(function) 
     1    2.794    2.794    2.794    2.794 {raw_input} 
     1    1.263    1.263    1.263    1.263 dictDel1.py:7(<dictcomp>) 
     1    1.030    1.030    1.030    1.030 dictDel1.py:9(<dictcomp>) <-- dict comprehension 
     1    0.892    0.892    0.976    0.976 dictDel1.py:11(del_iter) <-- resize while iterating 
     1    0.085    0.085    0.085    0.085 {method 'keys' of 'dict' objects} 
     1    0.000    0.000    0.000    0.000 {method 'iteritems' of 'dict' objects} 
     1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects} 

当 guard_condition = 8500000 时,输出为

ncalls  tottime  percall  cumtime  percall filename:lineno(function) 
     1    3.316    3.316    3.316    3.316 {raw_input} 
     1    1.247    1.247    1.247    1.247 dictDel1.py:7(<dictcomp>) 
     1    0.937    0.937    1.052    1.052 dictDel1.py:11(del_iter) <-- resize while iterating 
     1    0.787    0.787    0.787    0.787 dictDel1.py:9(<dictcomp>) <-- dict comprehension 
     1    0.115    0.115    0.115    0.115 {method 'keys' of 'dict' objects} 
     1    0.000    0.000    0.000    0.000 {method 'iteritems' of 'dict' objects} 
     1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}