In Python, the items() method is usually used for dictionary objects to return all key-value pairs of the dictionary. This is a member method of a dictionary, so you cannot use it directly on any object unless that object is a dictionary.
Here is an example:
# 创建一个字典 my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'} # 使用 items() 方法 items = my_dict.items() # 打印字典的键值对 for item in items: print(item)
This will output:
arduino ('name', 'Alice') ('age', 25) ('city', 'New York')
Each key-value pair is returned as a tuple, where the first element is the key , the second element is the value.
Note that items() returns a "view" object (in Python 3.3 and later), which means that it is a snapshot of the dictionary, reflecting the contents of the original dictionary. If you change the original dictionary, the view object will not be updated. If you want to create a new dictionary, you can use the dict() function, or use the list() function to convert the view to a list.
The above is the detailed content of How to use items in python. For more information, please follow other related articles on the PHP Chinese website!