dict.items() method in Python returns a view object containing all key-value pairs of the dictionary as tuples. This view updates automatically when the dictionary is modified. It is used when both keys and values are required together.
Example: In this example, items() is used to retrieve all key-value pairs from a dictionary.
d = {'A': 'Python', 'B': 'Java'}
print(d.items())
Output
dict_items([('A', 'Python'), ('B', 'Java')])
Explanation: d.items() returns a view object containing tuples of key and value pairs from d.
Note: items() method is only available for dictionary objects. If called on a non-dictionary object(like list, tuple etc.), it will raise an AttributeError.
Syntax
dict.items()
- Parameters: No parameters are required.
- Return value: Returns a dict_items view object containing (key, value) tuples.
Examples
Example 1: In this example, items() is used inside a loop to access keys and values together. This allows processing both elements in each iteration.
d = {'x': 10, 'y': 20}
for k, v in d.items():
print(k, v)
Output
x 10 y 20
Explanation: d.items() returns key-value tuples and for k, v in d.items() unpacks each tuple into k and v.
Example 2: In this example, dictionary is modified after calling items(). The view object reflects the updated content automatically.
d = {'a': 1, 'b': 2}
it = d.items()
d['c'] = 3
print(it)
Output
dict_items([('a', 1), ('b', 2), ('c', 3)])
Explanation: it = d.items() creates a view object, d['c'] = 3 updates the dictionary and 'it' automatically reflects the new pair.
Example 3: In this example, view object returned by items() is converted into a list. This allows using list operations.
d = {'p': 100, 'q': 200}
l = list(d.items())
print(l)
Output
[('p', 100), ('q', 200)]
Explanation: d.items() returns a view object and list(d.items()) converts it into a list of tuples.