How do you use the item function in Python?
In Python, the item function is used to return all key-value pairs in a dictionary, returning them as tuples. The usage of the item function is as follows:
# 创建一个字典
my_dict = {"name": "Alice", "age": 25, "country": "USA"}
# 使用item函数返回所有的键值对
items = my_dict.items()
# 遍历并打印所有的键值对
for key, value in items:
print(key, value)
The output is:
name Alice
age 25
country USA
In the example above, the items function returns an iterable object containing all the key-value pairs in the dictionary. We can use a for loop to iterate through and print these key-value pairs. In each iteration, use key and value to receive the key and value of each key-value pair.