Home > Article > Backend Development > How to use the items() function in Python
How to use the items() function in Python
The dictionary (dict) type in Python has a very useful built-in function - items(). The items() function is used to return all key-value pairs in the dictionary and convert it into an iterable object.
The basic syntax of the items() function is as follows:
dictionary.items()
Use the items() function to iterate through all key-value pairs in the dictionary. The specific usage is as follows:
# 创建一个字典 fruit_dict = {'apple': 5, 'banana': 10, 'orange': 3, 'grape': 8} # 使用items()函数遍历字典中的所有键值对 for key, value in fruit_dict.items(): print(key, value)
Run the above code, the output result is as follows:
apple 5 banana 10 orange 3 grape 8
As you can see, through the items() function, we get all the key-value pairs in the fruit_dict dictionary, and then Output one by one through a for loop.
In addition to using a for loop to traverse the key-value pairs in the dictionary, the items() function can also convert them to other data types, such as lists or tuples. The following is a sample code:
# 创建一个字典 fruit_dict = {'apple': 5, 'banana': 10, 'orange': 3, 'grape': 8} # 将字典中的键值对转换为列表 items_list = list(fruit_dict.items()) print(items_list) # 将字典中的键值对转换为元组 items_tuple = tuple(fruit_dict.items()) print(items_tuple)
Run the above code, the output is as follows:
[('apple', 5), ('banana', 10), ('orange', 3), ('grape', 8)] (('apple', 5), ('banana', 10), ('orange', 3), ('grape', 8))
By converting the key-value pairs in the dictionary into a list or tuple, we can use these data flexibly, Perform operations such as sorting and filtering.
In addition, using the items() function can also conveniently traverse and operate the dictionary. For example, the following code uses the items() function to count the types of fruits in the fruit_dict whose number is greater than or equal to 5:
# 创建一个字典 fruit_dict = {'apple': 5, 'banana': 10, 'orange': 3, 'grape': 8} # 使用items()函数对字典进行遍历和操作 for key, value in fruit_dict.items(): if value >= 5: print(key)
Run the above code, the output result is as follows:
apple banana grape
You can see that through Use the items() function to conveniently traverse the key-value pairs in the dictionary and perform operations based on conditions.
Summary: The items() function in Python is a very practical function that can easily traverse all key-value pairs in the dictionary and perform various operations. Whether it is traversing through a for loop, converting to a list or tuple, performing statistics, etc., the items() function can help us process key-value pairs in the dictionary quickly and efficiently. I hope that through the introduction and sample code of this article, readers can better understand and master the use of the items() function.
The above is the detailed content of How to use the items() function in Python. For more information, please follow other related articles on the PHP Chinese website!