python 示例
字典popitem()方法 (Dictionary popitem() Method)
popitem() method is used to remove random/last inserted item from the dictionary.
popitem()方法用于从字典中删除随机/最后插入的项目。
Before the Python version 3.7, it removes random item and from version 3.7, it removes last inserted item.
在Python 3.7之前的版本中,它会删除随机项,而在3.7版中,它会删除最后插入的项。
Syntax:
句法:
dictionary_name.popitem()
Parameter(s):
参数:
It does not accept any parameter.
它不接受任何参数。
Return value:
返回值:
The return type of this method is <class 'tuple'>, it returns the removed item as a tuple (key, value).
此方法的返回类型为<class'tuple'> ,它以元组(键,值)的形式返回已删除的项目。
Example 1:
范例1:
# Python Dictionary popitem() Method with Example
# dictionary declaration
student = {
"roll_no": 101,
"name": "Shivang",
"course": "B.Tech",
"perc" : 98.5
}
# printing dictionary
print("data of student dictionary...")
print(student)
# removing item
x = student.popitem()
print(x, ' is removed.')
# removing item
x = student.popitem()
print(x, ' is removed.')
Output (On Python version 3)
输出(在Python版本3上)
data of student dictionary...
{'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5, 'roll_no': 101}
('name', 'Shivang') is removed.
('course', 'B.Tech') is removed.
Output (On Python version 3.7.4)
输出(在Python版本3.7.4上)
data of student dictionary...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5}
('perc', 98.5) is removed.
('course', 'B.Tech') is removed.
Demonstrate the example, if no more item exists then it returns an error.
演示该示例,如果不存在任何其他项目,则返回错误。
Example 2:
范例2:
# Python Dictionary popitem() Method with Example
# dictionary declaration
temp = {
"key1": 1,
"key2": 2
}
# printing dictionary
print("data of temp dictionary...")
print(temp)
# popping item
x = temp.popitem()
print(x, 'is removed.')
# popping item
x = temp.popitem()
print(x, 'is removed.')
# popping item
x = temp.popitem()
print(x, 'is removed.')
Output
输出量
data of temp dictionary...
{'key2': 2, 'key1': 1}
('key2', 2) is removed.
('key1', 1) is removed.
Traceback (most recent call last):
File "main.py", line 22, in <module>
x = temp.popitem()
KeyError: 'popitem(): dictionary is empty'
翻译自: https://www.includehelp.com/python/dictionary-popitem-method-with-example.aspx
python 示例