为什么在Python中遍历字典时必须调用.items()? [英] Why do you have to call .items() when iterating over a dictionary in Python?
问题描述
为什么必须调用 items()
进行迭代超过键,字典中的值对?即.
Why do you have to call items()
to iterate over key, value pairs in a dictionary? ie.
dic = {'one': '1', 'two': '2'}
for k, v in dic.items():
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
会顺利通过-如果in
(循环子句)的一种含义与另一种(存在检查)的含义完全不同,您不会感到惊讶吗?我一定会的!它自然适用于列表,集合,元组,...
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
是字典时,如果in
要在for
循环中生成键/值元组,那么根据最小惊讶的原理,in
也必须采用这样的形式元组作为其在包含检查中的左侧操作数.
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.
那会有用吗?实际上,这实际上是没有用的,基本上使if (key, value) in C
成为if C.get(key) == value
的代名词–我认为这是我执行或想要执行的检查的次数,比if k in C
实际的意思少100倍. >,检查键 only 的存在并完全忽略该值.
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
同时具有该值也无济于事:
having the value as well would not help particularly:
for k, v in thedict.items():
thedict[k] = v + 1
实际上不太清晰和简洁. (请注意,items
是用于获取键/值对的正确"方法的原始拼写:不幸的是,这是在此类访问器返回整个列表的时代,因此,为了支持只是迭代",需要使用另一种拼写引入iteritems
就是-在Python 3中,与以前的Python版本的向后兼容性约束大大减弱,它又变成了items
.
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中遍历字典时必须调用.items()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!