Python3 字典 popitem() 方法

更新时间:2022-01-24 22:38
描述

Python 字典 popitem() 方法随机返回并删除字典中的最后一对键和值。如果字典已经为空,却调用了此方法,就报出KeyError异常。


语法
popitem()方法语法:
popitem()

参数


返回值

返回一个键值对(key,value)形式,按照 LIFO(Last In First Out 后进先出法) 顺序规则,即最末尾的键值对。


实例
以下实例展示了 popitem() 方法的使用方法:
#!/usr/bin/python3

site= {'name': '罗分明', 'alexa': 10000, 'url': 'www.luofenming.com'}
pop_obj=site.popitem()
print(pop_obj)  
print(site)
输出结果为:
('url', 'www.luofenming.com')
{'name': '罗分明', 'alexa': 10000}