What is the usage of items() method in Python dictionaries?
In Python dictionaries, the method items() is used to return a view of all the key-value pairs in the dictionary. Specifically, it returns a list of tuples, where each tuple contains a key from the dictionary and its corresponding value.
The usage of this method is as follows:
dictionary.items()
示例:解释一下这个观点。- Please explain this point.
student = {'name': 'Alice', 'age': 18, 'grade': 'A'}
items = student.items()
print(items)
Output:
dict_items([('name', 'Alice'), ('age', 18), ('grade', 'A')])
In the example above, the items() method returns a dictionary view called dict_items, which contains all the key-value pairs in the dictionary student. It is important to note that dictionary views are dynamic and will update accordingly when the dictionary changes.
You can use a for loop to iterate through all key-value pairs in a dictionary.
student = {'name': 'Alice', 'age': 18, 'grade': 'A'}
for key, value in student.items():
print(key, ':', value)
Output:
name : Alice
age : 18
grade : A
In the example above, we use a for loop to iterate through all key-value pairs in the dictionary ‘student’, assigning the key to variable ‘key’ and the value to variable ‘value’, then printing them out.