杰瑞科技汇

Python3中iteritems方法去哪了?替代方案是什么?

Of course! This is a great question that touches on a key change in Python 3.

Python3中iteritems方法去哪了?替代方案是什么?-图1
(图片来源网络,侵删)

Let's break it down.

The Short Answer

iteritems() does not exist in Python 3. It was a method from Python 2.

In Python 3, you should use the .items() method. It behaves like Python 2's iteritems() by default, returning a "dictionary view object" that is memory-efficient and provides an iterator.


The Detailed Explanation: Python 2 vs. Python 3

To understand why this change was made, you need to look at how dictionaries worked in Python 2.

Python3中iteritems方法去哪了?替代方案是什么?-图2
(图片来源网络,侵删)

In Python 2: Three Ways to Iterate

In Python 2, dictionaries had three different methods for getting key-value pairs, each with a different behavior:

  1. .items()

    • Behavior: Returned a list of (key, value) tuples.
    • Memory: High. It created an entirely new list in memory, which could be very expensive for large dictionaries.
    • Use Case: Useful if you needed to modify the list or use it multiple times, as it was a static copy.
    # Python 2
    d = {'a': 1, 'b': 2}
    items_list = d.items()
    print(items_list)
    # Output: [('a', 1), ('b', 2)]
    print(type(items_list))
    # Output: <type 'list'>
  2. .iteritems()

    • Behavior: Returned an iterator over the (key, value) pairs.
    • Memory: Very low. It didn't create a list. It yielded one item at a time as you looped through it.
    • Use Case: The preferred method for iteration, especially with large dictionaries, because it was memory-efficient.
    # Python 2
    d = {'a': 1, 'b': 2}
    items_iterator = d.iteritems()
    print(items_iterator)
    # Output: <dictionary-itemiterator object at 0x...>
    print(list(items_iterator)) # Converting the iterator to a list to see its contents
    # Output: [('a', 1), ('b', 2)]
  3. .viewitems()

    Python3中iteritems方法去哪了?替代方案是什么?-图3
    (图片来源网络,侵删)
    • Behavior: Returned a dictionary view object.
    • Memory: Low. The view object is a dynamic window into the dictionary's data. It doesn't store a copy of the items.
    • Use Case: Very powerful. If the dictionary changes, the view object reflects those changes. It also supports set-like operations (e.g., &, ).
    # Python 2
    d = {'a': 1, 'b': 2}
    items_view = d.viewitems()
    print(items_view)
    # Output: dict_items([('a', 1), ('b', 2)])
    print(type(items_view))
    # Output: <type 'dict_items'>

The Problem in Python 2

The existence of three separate methods was confusing. For the most common use case—iterating over a dictionary—developers had to remember to use the memory-efficient .iteritems() and avoid the slow .items().

The Solution in Python 3

The Python developers decided to simplify this. They wanted the most common and efficient behavior to be the default.

  • They removed .iteritems() and .viewitems().
  • They changed the behavior of .items().
  • In Python 3, .items() now returns a dictionary view object (which is also an iterator).

This new object has the best of both worlds:

  • It's memory-efficient (like the old .iteritems()).
  • It's dynamic (like the old .viewitems()).
  • It's the default, so you don't have to think about it.
# Python 3
d = {'a': 1, 'b': 2}
# In Python 3, d.items() is what you use for everything.
items_view = d.items()
print(items_view)
# Output: dict_items([('a', 1), ('b', 2)])
print(type(items_view))
# Output: <class 'dict_items'>
# It's an iterator, so you can loop over it directly
for key, value in items_view:
    print(f"Key: {key}, Value: {value}")
# It's dynamic. If the dictionary changes, the view changes.
d['c'] = 3
print(items_view)
# Output: dict_items([('a', 1), ('b', 2), ('c', 3)])

How to Handle Old Python 2 Code

If you are maintaining legacy Python 2 code or need to write code that works in both Python 2 and 3, you can use the six library, which provides compatibility helpers.

The six library has a function six.iteritems() that intelligently calls the correct method for the version of Python you are running.

pip install six
import six
# This code works in both Python 2 and Python 3
d = {'a': 1, 'b': 2}
# six.iteritems will call d.iteritems() in Python 2
# and d.items() in Python 3
for key, value in six.iteritems(d):
    print(f"Key: {key}, Value: {value}")

Summary Table

Method Python 2 Behavior Python 3 Behavior Recommendation
.items() Returns a list of tuples. Returns a dictionary view (iterator). Use this in Python 3.
.iteritems() Returns an iterator. Does not exist. AttributeError. Do not use in Python 3.
.viewitems() Returns a dictionary view. Does not exist. AttributeError. Do not use in Python 3.

Key Takeaways

  1. iteritems() is gone in Python 3.
  2. Use .items() in Python 3. It is the modern, correct, and most efficient way to get an iterable view of a dictionary's items.
  3. The change was made to promote the most memory-efficient behavior as the default, simplifying the API.
  4. For cross-compatible code (Python 2 & 3), use a library like six.
分享:
扫描分享到社交APP
上一篇
下一篇