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


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


產生隨機數在日常生活中有許多應用。在列表中,支持相同的各種函數。整個庫專用於Python處理隨機數。但是有時候,我們需要對字典執行類似的任務。

字典中的popitem()方法有助於實現類似的目的。它從字典中刪除任意鍵/值對,並將其作為元組返回。

用法:dict.popitem()
參數: None
返回: A tuple containing the arbitrary key-value pair from dictionary. That pair is removed from dictionary.

代碼1:演示popitem()的使用

# Python 3 code to demonstrate 
# working of popitem() 
  
# initializing dictionary  
test_dict = { "Nikhil" :7, "Akshat" :1, "Akash" :2 } 
  
# Printing initial dict 
print ("The dictionary before deletion:" + str(test_dict)) 
  
# using popitem() to return + remove arbitrary  
# pair 
res = test_dict.popitem() 
  
# Printing the pair returned 
print ('The arbitrary pair returned is:' + str(res)) 
  
# Printing dict after deletion 
print ("The dictionary after removal:" + str(test_dict))

輸出:

The dictionary before deletion:{'Nikhil':7, 'Akshat':1, 'Akash':2}
The arbitrary pair returned is:('Akash', 2)
The dictionary after removal:{'Nikhil':7, 'Akshat':1}

實際應用:此特定函數可用於製定玩遊戲的隨機名稱或確定隨機排名列表,而無需使用任何隨機函數。

代碼2:演示popitem()的應用

# Python 3 code to demonstrate 
# application of popitem() 
  
# initializing dictionary  
test_dict = { "Nikhil" :7, "Akshat" :1, "Akash" :2 } 
  
# Printing initial dict 
print ("The dictionary before deletion:" + str(test_dict)) 
  
n = len(test_dict) 
  
# using popitem to assign ranks 
for i in range(0, n):
    print ("Rank " + str(i + 1) + " " + str(test_dict.popitem())) 
  
# Printing end dict 
print ("The dictionary after deletion:" + str(test_dict))

輸出:

The dictionary before deletion:{'Nikhil':7, 'Akshat':1, 'Akash':2}
Rank 1 ('Akash', 2)
Rank 2 ('Akshat', 1)
Rank 3 ('Nikhil', 7)
The dictionary after deletion:{}



相關用法


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