<p>在回答一个特殊的问题时,我偶然发现了一个我无法解释的特殊问题。不幸的是,前两个Google搜索页面返回了一个<a href="https://stackoverflow.com/questions/2844837/how-to-fix-this-python-error-runtimeerror-dictionary-changed-size-during-itera">SO</a>页面,这也没有帮助。</p>
<p>问题代码</p>
<pre><code>>>> somedata=[random.randint(1,1000) for i in xrange(1,10000)]
>>> somehash=collections.defaultdict(int)
>>> for d in somedata:
somehash[d]+=1
>>> maxkey=0
>>> for k,v in somehash.iteritems():
if somehash[maxkey] > v:
maxkey=k
Traceback (most recent call last):
File "<pyshell#700>", line 1, in <module>
for k,v in somehash.iteritems():
RuntimeError: dictionary changed size during iteration
>>> for k,v in somehash.iteritems():
if somehash[maxkey] > v:
maxkey=k
>>>
</code></pre>
<p>由于一些奇怪的原因,当我第一次遍历字典时,Python正在发脾气,但是随后的执行很好,正如您在示例中看到的,当我第一次遍历字典时,它给出了运行时错误,但是下一次它没有抱怨。</p>
<p>知道怎么回事吗?</p>
<p>万一需要的话</p>
<pre><code>>>> sys.version_info
sys.version_info(major=2, minor=7, micro=0, releaselevel='final', serial=0)
>>> sys.version
'2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)]'
OS: Microsoft Windows [Version 6.1.7601] (Windows 7)
</code></pre>