當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Dictionary popitem()用法及代碼示例

字典 popitem() 方法

popitem() 方法用於從字典中刪除隨機/最後插入的項目。

在 Python 3.7 版之前,它刪除隨機項目,從 3.7 版開始,它刪除最後插入的項目。

用法:

    dictionary_name.popitem()

參數:

  • 它不接受任何參數。

返回值:

這個方法的返回類型是<class 'tuple'>,它將刪除的項目作為元組(鍵,值)返回。

範例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.')

輸出(在 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.

輸出(在 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.

演示示例,如果不存在更多項目,則返回錯誤。

範例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.')

輸出

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'


相關用法


注:本文由純淨天空篩選整理自 Python Dictionary popitem() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。