为什么在python中迭代一个字典时必须调用.iteritems()? [英] Why do you have to call .iteritems() when iterating over a dictionary in python?
问题描述
为什么要调用 iteritems()
来迭代字典中的键值?即
Why do you have to call iteritems()
to iterate over key, value pairs in a dictionary? ie
dic = {'one':'1', 'two':'2'}
for k, v in dic.iteritems():
print k, v
为什么不在字典中迭代的默认行为
Why isn't that the default behavior of iterating over a dictionary
for k, v in dic:
print k, v
推荐答案
对于每个python容器C,期望是
For every python container C, the expectation is that
for item in C:
assert item in C
将通过正确 - 不会你发现令人惊讶的是,如果 >(循环子句)与另一个(存在检查)有完全不同的意义?我肯定会!对于列表,集合,元组,...自然可以这样做。
will pass just fine -- wouldn't you find it astonishing if one sense of in
(the loop clause) had a completely different meaning from the other (the presence check)? I sure would! It naturally works that way for lists, sets, tuples, ...
所以,当 C
是一个字典,如果中的在
中的中为
循环产生键/值元组,那么以最不惊讶的原则, 也必须在遏制检查中使用左手操作数的元组。
So, when C
is a dictionary, if in
were to yield key/value tuples in a for
loop, then, by the principle of least astonishment, in
would also have to take such a tuple as its left-hand operand in the containment check.
如何有用会是吗如果C.get(key)== value $ c,则基本上使code> if(key,value)在C 中是的同义词$ c> - 这是一个支票,我相信我可能已经执行了,或者想要执行,比C
中的k实际意味着,检查密钥的存在,并完全忽略该值。
How useful would that be? Pretty useless indeed, basically making if (key, value) in C
a synonym for if C.get(key) == value
-- which is a check I believe I may have performed, or wanted to perform, 100 times more rarely than what if k in C
actually means, checking the presence of the key only and completely ignoring the value.
另一方面,想要在密钥上循环很常见,例如:
On the other hand, wanting to loop just on keys is quite common, e.g.:
for k in thedict:
thedict[k] += 1
有价值也不会有帮助:
for k, v in thedict.items():
thedict[k] = v + 1
实际上有些不太清楚,不太简洁。 (请注意,项目
是使用正确方法获取键/值对的原始拼写:不幸的是,在这些访问者返回整个列表的日子里,所以要支持只是迭代,必须引入一个替代的拼写,而在Python 3中,这是一个与之前的Python版本的向后兼容性约束很大程度的削弱的 iteritems
它再次成为项目
。
actually somewhat less clear and less concise. (Note that items
was the original spelling of the "proper" methods to use to get key/value pairs: unfortunately that was back in the days when such accessors returned whole lists, so to support "just iterating" an alternative spelling had to be introduced, and iteritems
it was -- in Python 3, where backwards compatibility constraints with previous Python versions were much weakened, it became items
again).
这篇关于为什么在python中迭代一个字典时必须调用.iteritems()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!