Python Dictionary items() Method
The items()
method returns a view object that displays a list of dictionary’s key-value pairs as tuples. This view object is dynamic, meaning any changes made to the dictionary will be reflected in the view object.
Syntax
dictionary.items()
Parameters
The items()
method doesn’t accept any parameters.
Return Value
The items()
method returns a view object that displays a list of dictionary’s key-value pairs as tuples.
Example:
person = {"name": "James", "age": 35, "city": "New York"}
print(person.items()) # Output: dict_items([('name', 'James'), ('age', 35), ('city', 'New York')])
Iterating through key-value pairs of a dictionary
The view object returned by the items()
method is iterable, meaning you can loop over it directly.
For example:
person = {"name": "James", "age": 35, "city": "New York"}
# Iterating through key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
Output:
name: James
age: 35
city: New York
Converting view object to list
You can convert the view object to a list using the list()
function if needed.
For example:
person = {"name": "James", "age": 35, "city": "New York"}
items_view = person.items()
# Convert view object to list
items_list = list(items_view)
print(items_list)
Output:
[('name', 'James'), ('age', 35), ('city', 'New York')]
View object is dynamic
The view object returned by the items()
method is dynamic, meaning if the dictionary is modified after the view object is created, the changes are reflected in the view object.
For example:
person = {"name": "James", "age": 35}
# Creating a view object
items_view = person.items()
# Modifying the dictionary
person["city"] = "Austin"
print(items_view)
Output:
dict_items([('name', 'James'), ('age', 35), ('city', 'Austin')])
The items()
method is useful for simultaneously iterating over both keys and values of a dictionary.