作为初学python的菜鸟一枚,今天复习的是字典函数。
1、字典函数是用{ }表示的。字典里'k' 与'v'即键与值是一 一对应的。
2、字典函数 keys 、 values、 items分别对应字典的键、值和键-值对。
例 :>>> spam = {'name': 'Mary', 'color': 'red', 'age': '25'}
>>> spam.keys()
dict_keys(['color', 'name', 'age'])
>>> spam.values()
dict_values(['red', 'Mary', '25'])
>>> spam.items()
dict_items([('color', 'red'), ('name', 'Mary'), ('age', '25')])
>>> spam.keys()
dict_keys(['color', 'name', 'age'])
>>> spam.values()
dict_values(['red', 'Mary', '25'])
>>> spam.items()
dict_items([('color', 'red'), ('name', 'Mary'), ('age', '25')])
3、还可以通过字典的某一键访问这个键对应的值。若访问的键不存在,则会有KeyError出错信息。
>>> spam = {'name': 'Mary', 'color': 'red', 'age': '25'}
>>> spam['name']
'Mary'
>>> spam['name']
'Mary'
这里访问键对应的值要用方括号。
4、字典不能像列表那样切片,因为字典是不排序的。
5 in 或not in 检查某个键或值是否存在于字典中。
例:>>> spam = {'name': 'Mary', 'color': 'red', 'age': '25'}
>>> 'name' in spam.keys() # 'name' in spam 是简写版本
True6
>>> 'name' in spam.keys() # 'name' in spam 是简写版本
True6
6、get( )函数:在访问一个键的值之前,检查该键是否存在于字典中。get(a, b)有2个参数,第一个参数是访问字典中的这个键,第2个参数是该键不存在的时候返回的备用值。
例:>>> picnicItems = {'apples': 5, 'cups': 2}
>>> 'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups'
'I am bringing 2 cups'
'I am bringing 2 cups'
>>> 'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' cups'
'I am bringing 0 cups'