接口测试 python 中字典 dict 的部分函数

meiyo · 2018年03月06日 · 1046 次阅读

dict.update([other])函数

dict.update()使用来自other的键/值对更新字典,同时重写已存在的关键字的值,并返回None
update()函数接受一个参数other,其或者是一个字典对象,或者是一个可迭代的键/值对(作为元组,或者长度为 2 的可迭代对象)。如果other是关键字参数,字典dict使用这些键值对更新:d.update(red=2, blue=2)

>>> def key(v):
...     return (v, v)
... 
>>> value = range(3)
>>> map(key, value)
>>> product = {}
>>> product.update(map(key, value))
>>> product
{0: 0, 1: 1, 2: 2}

dict.get(key[,default])函数

如果key在字典dict中,返回其对应的值;否则返回default,若未给定default,默认返回None。所以,这个方法不会抛异常KeyError

>>> dict = {'a':1, 'b':2}
>>> dict.get('a')
1
>>> dict.get('c', 3)
3
>>> dict.get('c')

dict.pop(key[,default])函数

如果key在字典dict中,删除该键值对并返回其对应的值;否则返回default,若未给定defaultkey不在字典dict中,会抛异常KeyError

>>> dict = {'a':1, 'b':2, 'c':3}
>>> dict.pop('b')
2
>>> dict
{'a': 1, 'c': 3}
>>> dict.pop('d')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: 'd'
>>> dict.pop('d', 6)
6
>>> dict
{'a': 1, 'c': 3}

dict.popitem([other])函数

删除并返回一个任意的(这里的"任意"并不是随机,各个版本实现删除的顺序不一样,有的是删除第一个键值对,有的是删除最后一个键值对)dict(key, value) 对。如果dict为空,调用 calling popitem()会抛出 KeyError异常。

>>> d = {'a':1, 'b':2, 'c':3}
>>> d.popitem()
('c', 3)
>>> d.popitem()
('b', 2)
>>> d.popitem()
('a', 1)
>>> d.popitem()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: 'popitem(): dictionary is empty'
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册