python popitem()方法删除字典最后键值对
popitem()方法
popitem()方法,为python字典dict内置的实例方法,可以用来删除调用对象字典最后键值对,如果空字典调用了popitem()方法,python会抛出KeyError。
popitem()语法及参数结构
dict.popitem()
popitem()方法不接收参数,否则python会抛出TypeError。
popitem()返回值
popitem()方法返回由被删除的键值对组成的tuple元组,如(key, value)。
popitem()实例代码
>>> {}.popitem() #空字典调用popitem()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'popitem(): dictionary is empty'
>>> {'a':1}.popitem(1) #传递参数给popitem()方法,python抛出TypeError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: popitem() takes no arguments (1 given)
>>> {'a':1}.popitem()
('a', 1)
>>> type({'a':1}.popitem()) #popitem()方法返回值的类型为tuple
<class 'tuple'>
>>> d = {'网址':'x1y1z1.com','名称':'笨鸟工具'}
>>> d.popitem()
('名称', '笨鸟工具')
>>> d
{'网址': 'x1y1z1.com'}