背景:接口测试中response返回的都是json格式,基本可以理解为python的字典类型(我是这么理解的),所以呢我觉得python常用的一些方法,总结了一下,方便自己记忆。
>>> dict1={'a':1,'b':2}
>>> dict2={'c':3}
#update()往字典里面增加键值对
>>> dict1={'a':1,'b':2}
>>> dict2={'c':3}
>>> dict1.update(dict2)
>>> print dict1
{'a': 1, 'c': 3, 'b': 2}
#已经知道key取value值
>>> dict1['a']
1
#通过get(key,default)方法去值,这里面有一个参数default,用处是当key不存在时会将default值附上去,不会抛出异常.但是不会吧不存在key添加到字典中>>> print ("no key:"+str(dict1.get('d',4)))
no key:4
#get()方法是不会吧不存在key添加中原字典中,取非法key让然会抛异常,例如:>>> dict1('d')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable
#setdefault(key,default)这个和get()最大的区别就是如果你要查找的key不存在,不会抛异常并且会把新增加键值对添加到原字典中>>> print ("setdefault:"+str(dict1.setdefault('e',5)))
setdefault:5
>>> dict1['e']
5
#遍历字典中value>>> for value in dict1.values():
... print value
...
1
3
2
5
#遍历字典中key>>> for key in dict1.keys():
... print key
...
a
c
b
e
#遍历字典中key,values>>> for key,values in dict1.items():
... print (key,values)
...
('a', 1)
('c', 3)
('b', 2)
('e', 5)
#使用items()返回列表类型>>> dict1.items()
[('a', 1), ('c', 3), ('b', 2), ('e', 5)]
来活了,回头再用到什么补上吧