产生随机数在日常生活中有许多应用。在列表中,支持相同的各种函数。整个库专用于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:{}
相关用法
- Python dict pop()用法及代码示例
- Python dict setdefault()用法及代码示例
- Python dict update()用法及代码示例
- Python dict keys()用法及代码示例
- Python dict fromkeys()用法及代码示例
- Python dict items()用法及代码示例
注:本文由纯净天空筛选整理自manjeet_04大神的英文原创作品 Python Dictionary | popitem() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。