How to Use dict.items()
Method in Python?
dict.items()
method is used to get a view object containing the key-value pairs of the dictionary.
This view object can be used to iterate over the key-value pairs, convert them to a list, or perform other operations on the items of the dictionary.
# Dictionary containing information about a person
person = {
'name': 'John Doe',
'age': 30,
'occupation': 'Engineer',
'email': 'john@example.com'
}
# Get a view object of the key-value pairs
items_view = person.items()
Syntax
dict.items()
How to Use dict.items Method in Python
# Dictionary containing information about a person
person = {
'name': 'John Doe',
'age': 30,
'occupation': 'Engineer',
'email': 'john@example.com'
}
# Get a view object of the key-value pairs
items_view = person.items()
# Iterate over the key-value pairs and print them
for key, value in items_view:
print(f"{key}: {value}")
# Output:
# name: John Doe
# age: 30
# occupation: Engineer
# email: john@example.com
# Convert the view object to a list of key-value pairs
items_list = list(items_view)
print(items_list)
# Output: [('name', 'John Doe'), ('age', 30), ('occupation', 'Engineer'),
# ('email', 'john@example.com')]