为什么在 Python 中迭代字典时必须调用 .items()? [英] Why do you have to call .items() when iterating over a dictionary in Python?

查看:40
本文介绍了为什么在 Python 中迭代字典时必须调用 .items()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要调用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 倍,只检查键的存在并完全忽略该值.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆