Python Dictionary items() method
items() method in Python returns a view object that contains all the key-value pairs in a dictionary as tuples. This view object updates dynamically if the dictionary is modified.
Example:
d = {'A': 'Python', 'B': 'Java', 'C': 'C++'}
# using items() to get all key-value pairs
items = d.items()
print(items)
Output
dict_items([('A', 'Python'), ('B', 'Java'), ('C', 'C++')])
Explanation: items() method returns a dict_items view object containing all key-value pairs in the form of tuples.
Note : items() method is only available for dictionary objects. If called on a non-dictionary object, it will raise an AttributeError.
items() syntax
dict.items()
Here, dict is the dictionary from which the key-value pairs are retrieved.
Parameters:
- items() method does not take any parameters.
Return value:
- This method returns a
dict_items
view object, which behaves like a list of(key, value)
tuples. If the dictionary is updated, the view object automatically reflects these changes.
Examples of items()
Example 1: Iterating over key-value pairs
d = {'A': 'Python', 'B': 'Java', 'C': 'C++'}
# using items() to iterate over dictionary
for key, value in d.items():
print(f"Key: {key}, Value: {value}")
Output
Key: A, Value: Python Key: B, Value: Java Key: C, Value: C++
Explanation: items() method allows easy unpacking of key-value pairs using tuple unpacking inside a loop.
Example 2: Dynamic nature of items()
d = {'A': 'Python', 'B': 'Java'}
# getting items
items = d.items()
# adding a new key-value pair
d['C'] = 'C++'
print(items)
Output
dict_items([('A', 'Python'), ('B', 'Java'), ('C', 'C++')])
Explanation: When a new key-value pair is added to the dictionary, the items() view object updates automatically to include the new pair.
Example 3: Converting items() to a list
d = {'A': 'Python', 'B': 'Java', 'C': 'C++'}
# converting items to a list
items_list = list(d.items())
print(items_list)
Output
[('A', 'Python'), ('B', 'Java'), ('C', 'C++')]
Explanation: We convert the dict_items object into a list of tuples, allowing for indexing, sorting or other list operations.