据我所知,Python 字典是一个哈希表,如果表的大小超过当前表最大大小的 2/3 ( Objects\dictnotes.txt ),它就会调整大小。
我需要删除大量字典项目(数千个),例如,每小时一次,基于简单的标准 - if key <= 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}
关于Python:从字典中删除大量键的最快策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22668574/