在 Python 3 中迭代字典 items()、values()、keys()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3616721/
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 11:57:48  来源:igfitidea点击:

Iterating over dictionary items(), values(), keys() in Python 3

pythonpython-3.xdictionaryiterator

提问by max

If I understand correctly, in Python 2, iter(d.keys())was the same as d.iterkeys(). But now, d.keys()is a view, which is in between the list and the iterator. What's the difference between a view and an iterator?

如果我理解正确的话,在 Python 2 中,iter(d.keys())d.iterkeys(). 但是现在,d.keys()是一个视图,它位于列表和迭代器之间。视图和迭代器有什么区别?

In other words, in Python 3, what's the difference between

换句话说,在 Python 3 中,有什么区别

for k in d.keys()
    f(k)

and

for k in iter(d.keys())
    f(k)

Also, how do these differences show up in a simple forloop (if at all)?

此外,这些差异如何在一个简单的for循环中显示出来(如果有的话)?

采纳答案by mikej

I'm not sure if this is quite an answer to your questions but hopefully it explains a bit about the difference between Python 2 and 3 in this regard.

我不确定这是否能很好地回答您的问题,但希望它能稍微解释一下 Python 2 和 3 在这方面的区别。

In Python 2, iter(d.keys())and d.iterkeys()are not quite equivalent, although they will behave the same. In the first, keys()will return a copy of the dictionary's list of keys and iterwill then return an iterator object over this list, with the second a copy of the full list of keys is never built.

在Python 2,iter(d.keys())d.iterkeys()不太等价的,尽管它们具有相同的行为。在第一个中,keys()将返回字典的键列表的副本,iter然后将在此列表上返回一个迭代器对象,第二个是从不构建完整键列表的副本。

The view objects returned by d.keys()in Python 3 are iterable(i.e. an iterator can be made from them) so when you say for k in d.keys()Python will create the iterator for you. Therefore your two examples will behave the same.

d.keys()Python 3 中返回的视图对象是可迭代的(即可以从它们for k in d.keys()生成迭代器),因此当您说Python 会为您创建迭代器。因此,您的两个示例的行为相同。

The significance in the change of the return type for keys()is that the Python 3 view object is dynamic. i.e. if we say ks = d.keys()and later add to dthen kswill reflect this. In Python 2, keys()returns a list of all the keys currently in the dict. Compare:

返回类型变化的意义在于keys()Python 3 视图对象是动态的。即如果我们说ks = d.keys()然后添加到d然后ks将反映这一点。在 Python 2 中,keys()返回当前在 dict 中的所有键的列表。相比:

Python 3

蟒蛇 3

>>> d = { "first" : 1, "second" : 2 }
>>> ks = d.keys()
>>> ks
dict_keys(['second', 'first'])
>>> d["third"] = 3
>>> ks
dict_keys(['second', 'third', 'first'])

Python 2.x

蟒蛇 2.x

>>> d = { "first" : 1, "second" : 2 }
>>> ks = d.keys()
>>> ks
['second', 'first']
>>> d["third"] = 3
>>> ks
['second', 'first']

As Python 3's keys()returns the dynamic object Python 3 doesn't have (and has no need for) a separate iterkeysmethod.

当 Python 3keys()返回动态对象时,Python 3 没有(也不需要)单独的iterkeys方法。

Further clarification

进一步澄清

In Python 3, keys()returns a dict_keysobject but if we use it in a forloop context for k in d.keys()then an iterator is implicitly created. So the difference between for k in d.keys()and for k in iter(d.keys())is one of implicit vs. explicit creation of the iterator.

在 Python 3 中,keys()返回一个dict_keys对象,但如果我们在for循环上下文中使用它,for k in d.keys()则会隐式创建一个迭代器。所以之间的区别for k in d.keys()for k in iter(d.keys())隐含对明确创建迭代器之一。

In terms of another difference, whilst they are both dynamic, remember if we create an explicit iterator then it can only be used once whereas the view can be reused as required. e.g.

就另一个区别而言,虽然它们都是动态的,但请记住,如果我们创建了一个显式迭代器,那么它只能使用一次,而视图可以根据需要重用。例如

>>> ks = d.keys()
>>> 'first' in ks
True
>>> 'second' in ks
True
>>> i = iter(d.keys())
>>> 'first' in i
True
>>> 'second' in i
False             # because we've already reached the end of the iterator

Also, notice that if we create an explicit iterator and then modify the dict then the iterator is invalidated:

另外,请注意,如果我们创建一个显式迭代器,然后修改 dict 则迭代器将失效:

>>> i2 = iter(d.keys())
>>> d['fourth'] = 4
>>> for k in i2: print(k)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration

In Python 2, given the existing behaviour of keysa separate method was needed to provide a way to iterate without copying the list of keys whilst still maintaining backwards compatibility. Hence iterkeys()

在 Python 2 中,考虑到keys单独方法的现有行为,需要提供一种在不复制键列表的情况下进行迭代的方法,同时仍保持向后兼容性。因此iterkeys()