Python 什么时候应该使用 iteritems() 而不是 items()?

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

When should iteritems() be used instead of items()?

pythonpython-3.x

提问by

Is it legitimate to use items()instead of iteritems()in all places? Why was iteritems()removed from Python 3? Seems like a terrific and useful method. What's the reasoning behind it?

在所有地方使用items()而不是合法iteritems()吗?为什么iteritems()从 Python 3中删除?似乎是一个了不起且有用的方法。背后的原因是什么?

Edit:To clarify, I want to know what is the correct idiom for iterating over a dictionary in a generator-like way (one item at a time, not all into memory) in a way that is compatible with both Python 2 and Python 3?

编辑:为了澄清,我想知道以与 Python 2 和 Python 3 兼容的方式以类似生成器的方式(一次一个项目,而不是全部进入内存)迭代字典的正确习惯用法是什么?

采纳答案by Jon Clements

In Python 2.x - .items()returned a list of (key, value) pairs. In Python 3.x, .items()is now an itemviewobject, which behaves different - so it hasto be iterated over, or materialised... So, list(dict.items())is required for what was dict.items()in Python 2.x.

在 Python 2.x 中 -.items()返回(键,值)对的列表。在 Python 3.x 中,.items()现在是一个itemview行为不同的对象 - 所以它必须被迭代或物化......所以,在 Python 2.x 中list(dict.items())是必需的dict.items()

Python 2.7 also has a bit of a back-port for key handling, in that you have viewkeys, viewitemsand viewvaluesmethods, the most useful being viewkeyswhich behaves more like a set(which you'd expect from a dict).

Python 2.7 也有一些用于密钥处理的后向端口,因为你有viewkeys,viewitemsviewvalues方法,最有用的是viewkeys它的行为更像 a set(你期望 a dict)。

Simple example:

简单的例子:

common_keys = list(dict_a.viewkeys() & dict_b.viewkeys())

Will give you a list of the common keys, but again, in Python 3.x - just use .keys()instead.

会给你一个常用键的列表,但同样,在 Python 3.x 中 - 只需使用.keys()

Python 3.x has generally been made to be more "lazy" - i.e. mapis now effectively itertools.imap, zipis itertools.izip, etc.

Python 3.x 通常被设计得更加“懒惰”——即map现在是有效的itertools.imapzipitertools.izip,等等。

回答by Wessie

dict.iteritemswas removed because dict.itemsnow does the thing dict.iteritemsdid in python 2.x and even improved it a bit by making it an itemview.

dict.iteritems被删除了,因为dict.items现在dict.iteritems在 python 2.x 中做了这件事,甚至通过将它变成一个itemview.

回答by goncalopp

As the dictionary documentation for python 2and python 3would tell you, in python 2 itemsreturns a list, while iteritemsreturns a iterator.

正如python 2python 3的字典文档会告诉你的那样,在 python 2 中items返回一个列表,而iteritems返回一个迭代器。

In python 3, itemsreturns a view, which is pretty much the same as an iterator.

在 python 3 中,items返回一个view,它与迭代器几乎相同。

If you are using python 2, you may want to user iteritemsif you are dealing with large dictionaries and all you want to do is iterate over the items (not necessarily copy them to a list)

如果您使用的是 python 2,iteritems如果您正在处理大型字典并且您想要做的就是遍历项目(不一定将它们复制到列表中),则可能需要用户

回答by YaOzI

Just as @Wessie noted, dict.iteritems, dict.iterkeysand dict.itervalues(which return an iteratorin Python2.x) as well as dict.viewitems, dict.viewkeysand dict.viewvalues(which return view objectsin Python2.x) were all removed in Python3.x

正如@Wessie 指出的那样,dict.iteritems,dict.iterkeysdict.itervalues(在 Python2.x 中返回一个迭代器)以及dict.viewitems,dict.viewkeysdict.viewvalues(在 Python2.x 中返回视图对象)在 Python3.x 中都被删除了

And dict.items, dict.keysand dict.valuesused to return a copyof the dictionary's list in Python2.x now return view objectsin Python3.x, butthey are still not the same as iterator.

而且dict.itemsdict.keysdict.values用于返回一个副本中Python2.x字典的名单现在返回视图对象在Python3.x,他们还是不一样的迭代器

If you want to return an iteratorin Python3.x, use iter(dictview):

如果要在 Python3.x 中返回迭代器,请使用iter(dictview)

$ python3.3

>>> d = {'one':'1', 'two':'2'}
>>> type(d.items())
<class 'dict_items'>
>>>
>>> type(d.keys())
<class 'dict_keys'>
>>>
>>>
>>> ii = iter(d.items())
>>> type(ii)
<class 'dict_itemiterator'>
>>>
>>> ik = iter(d.keys())
>>> type(ik)
<class 'dict_keyiterator'>

回答by Florian Winter

You cannot use itemsinstead iteritemsin all places in Python. For example, the following code:

不能使用items,而不是iteritems在所有的Python的地方。例如,以下代码:

class C:
  def __init__(self, a):
    self.a = a
  def __iter__(self):
    return self.a.iteritems()

>>> c = C(dict(a=1, b=2, c=3))
>>> [v for v in c]
[('a', 1), ('c', 3), ('b', 2)]

will break if you use items:

如果您使用,则会中断items

class D:
  def __init__(self, a):
    self.a = a
  def __iter__(self):
    return self.a.items()

>>> d = D(dict(a=1, b=2, c=3))
>>> [v for v in d]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __iter__ returned non-iterator of type 'list'

The same is true for viewitems, which is available in Python 3.

viewitems也是如此,它在 Python 3 中可用。

Also, since itemsreturns a copy of the dictionary's list of (key, value)pairs, it is less efficient, unless you want to create a copy anyway.

此外,由于items返回字典对列表的副本(key, value),因此效率较低,除非您无论如何都想创建副本。

In Python 2, it is best to use iteritemsfor iteration. The 2to3tool can replace it with itemsif you ever decide to upgrade to Python 3.

在 Python 2 中,最好iteritems用于迭代。如果您决定升级到 Python 3,该2to3工具可以替换它items

回答by Dean Serenevy

The six libraryhelps with writing code that is compatible with both python 2.5+ and python 3. It has an iteritems method that will work in both python 2 and 3. Example:

六个库有助于编写与 python 2.5+ 和 python 3 兼容的代码。它有一个适用于 python 2 和 python 3 的 iteritems 方法。示例:

import six

d = dict( foo=1, bar=2 )

for k, v in six.iteritems(d):
    print(k, v)

回答by Daniel

future.utils allows for python 2 and 3 compatibility

future.utils 允许与 python 2 和 3 兼容

# Python 2 and 3: option 3
from future.utils import iteritems
heights = {'man': 185,'lady': 165}
for (key, value) in iteritems(heights):
    print(key,value)

>>> ('lady', 165)
>>> ('man', 185)

https://python-future.org/compatible_idioms.html

https://python-future.org/compatible_idioms.html