dict.pop() 与 dict.popitem()
dict.pop(key) : Python 字典 pop() 方法删除字典给定键 key 所对应的值,返回值为被删除的值。
语法 :
pop(key[,default])
default : 当key不存在时, 返回指定的默认值
如果字典已经为空,却调用了此方法,就报出 KeyError 异常。
In [1]: dict = {'a':1,'b':2,'c':3,'d':4}
In [2]: dict.pop('e','xxx')
Out[2]: 'xxx'
In [3]: dict.pop('c')
Out[3]: 3
In [4]: dict
Out[4]: {'a': 1, 'b': 2, 'd': 4}
In [5]: a = {}
In [6]: a.pop('a')
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Input In [6], in <cell line: 1>()
----> 1 a.pop('a')
KeyError: 'a'
dict.popitem(): 删除字典最后一个键值对, 并返回该键值对 ,返回形式为 (key,value)
语法:
popitem() 不需要传参
Python 字典 popitem() 方法返回并删除字典中的最后一对键和值, 返回一个键值对(key,value)形式。
如果字典已经为空,却调用了此方法,就报出 KeyError 异常。
In [7]: m = {'a':1,'b':2,'c':3,'d':4}
In [8]: m.popitem()
Out[8]: ('d', 4)
In [9]: m
Out[9]: {'a': 1, 'b': 2, 'c': 3}
In [10]: n = {}
In [11]: n.popitem()
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Input In [11], in <cell line: 1>()
----> 1 n.popitem()
KeyError: 'popitem(): dictionary is empty'
In [12]: m.popitem()
Out[12]: ('c', 3)
In [13]: m.popitem('a')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [13], in <cell line: 1>()
----> 1 m.popitem('a')
TypeError: dict.popitem() takes no arguments (1 given)
钟声敲响了日落,柏油路跃过山坡,一直通向北方的是我们想象,长大后也未曾经过~

浙公网安备 33010602011771号