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 示例