Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the difference between dict.items() and dict.iteritems() in Python?
In Python, dict.items() and dict.iteritems() are methods used to access dictionary key-value pairs. The key difference is that dict.items() returns a list of tuple pairs in Python 2 (dict_items view in Python 3), while dict.iteritems() returns an iterator over the dictionary's (key, value) pairs. Note that dict.iteritems() was removed in Python 3.
dict.items() in Python 2
In Python 2, dict.items() returns a list of tuples ?
# Python 2 syntax (cannot run online)
my_dict = {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
print(my_dict.items())
print(type(my_dict.items()))
[(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] <type 'list'>
dict.iteritems() in Python 2
In Python 2, dict.iteritems() returns an iterator for memory-efficient iteration ?
# Python 2 syntax (cannot run online)
states = {'Telangana': 'Hyderabad', 'Tamilnadu': 'Chennai', 'Karnataka': 'Bangalore'}
print(type(states.iteritems()))
for state, capital in states.iteritems():
print(state, capital)
<type 'dictionary-itemiterator'>
('Telangana', 'Hyderabad')
('Karnataka', 'Bangalore')
('Tamilnadu', 'Chennai')
dict.items() in Python 3
In Python 3, dict.items() returns a dictionary view object ?
my_dict = {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
items_view = my_dict.items()
print(items_view)
print(type(items_view))
# Convert to list if needed
print(list(items_view))
dict_items([(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]) <class 'dict_items'> [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
dict.iteritems() Error in Python 3
Using dict.iteritems() in Python 3 raises an AttributeError ?
my_dict = {"name": "Alice", "age": 21, "branch": "Computer Science"}
try:
for item in my_dict.iteritems():
print(item)
except AttributeError as e:
print(f"Error: {e}")
Error: 'dict' object has no attribute 'iteritems'
Comparison
| Method | Python 2 Return Type | Python 3 Availability | Memory Usage |
|---|---|---|---|
dict.items() |
List of tuples | Available (returns dict_items view) | Higher in Python 2 |
dict.iteritems() |
Iterator | Removed | Lower (lazy evaluation) |
Migration from Python 2 to 3
To migrate code using iteritems(), simply replace it with items() ?
# Python 3 equivalent of iteritems()
person = {"name": "Alice", "age": 25, "city": "New York"}
# This works in Python 3 (like iteritems() in Python 2)
for key, value in person.items():
print(f"{key}: {value}")
name: Alice age: 25 city: New York
Conclusion
In Python 2, use iteritems() for memory-efficient iteration and items() for list operations. In Python 3, only items() exists and provides an efficient view object that behaves like the old iteritems().
