为什么在 Python 中迭代字典时必须调用 .items() ?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3744568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:31:20  来源:igfitidea点击:

Why do you have to call .items() when iterating over a dictionary in Python?

pythonloopsdictionary

提问by Falmarri

Why do you have to call items()to iterate over key, value pairs in a dictionary? ie.

为什么必须调用items()迭代字典中的键值对?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)

采纳答案by Alex Martelli

For every python container C, the expectation is that

对于每个 python 容器 C,期望是

for item in C:
    assert item in C

will pass just fine -- wouldn't youfind 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, ...

会顺利通过——如果(循环子句)的一种含义与另一种(存在检查)的含义完全不同,会不会感到惊讶in?我肯定会!它自然适用于列表、集合、元组……

So, when Cis a dictionary, if inwere to yield key/value tuples in a forloop, then, by the principle of least astonishment, inwould also have to take such a tuple as its left-hand operand in the containment check.

因此,当C是字典时,如果in要在for循环中生成键/值元组,那么根据最小惊讶原则,in在包含检查中也必须采用这样的元组作为其左侧操作数。

How useful would that be? Pretty useless indeed, basically making if (key, value) in Ca 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 Cactually means, checking the presence of the key onlyand completely ignoring the value.

那会有多大用处?好看不中用的确,基本上做if (key, value) in C的代名词if C.get(key) == value-这是一张支票,我相信我可能已经执行,或要执行,100倍以上的很少比if k in C实际手段,检查钥匙的存在唯一,完全无视值。

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

actually somewhat less clear and less concise. (Note that itemswas 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 iteritemsit was -- in Python 3, where backwards compatibility constraints with previous Python versions were much weakened, it became itemsagain).

实际上有点不那么清晰和简洁。(请注意,这items是用于获取键/值对的“正确”方法的原始拼写:不幸的是,那是在此类访问器返回整个列表的时代,因此为了支持“仅迭代”,必须引入替代拼写,而且iteritems它是 - 在 Python 3 中,与以前的 Python 版本的向后兼容性约束大大削弱了,它又变成items了)。

回答by John Kugelman

My guess:Using the full tuple would be more intuitive for looping, but perhaps less so for testing for membership using in.

我的猜测:使用完整元组对于循环会更直观,但对于使用in.

if key in counts:
    counts[key] += 1
else:
    counts[key] = 1

That code wouldn't really work if you had to specify both key and value for in. I am having a hard time imagining use case where you'd check if both the key AND value are in the dictionary. It is far more natural to only test the keys.

如果您必须为in. 我很难想象你会检查键和值是否都在字典中的用例。只测试密钥要自然得多。

# When would you ever write a condition like this?
if (key, value) in dict:

Now it's not necessary that the inoperator and for ... inoperate over the same items. Implementation-wise they are different operations (__contains__vs. __iter__). But that little inconsistency would be somewhat confusing and, well, inconsistent.

现在没有必要让in运营商和for ... in运营商操作相同的项目。在实现方面,它们是不同的操作(__contains__vs. __iter__)。但是这种小小的不一致会让人有些困惑,而且,不一致。