Python基础 第四章 字典(2)字典方法&章小结
1. clear
方法clear删除所有的字典项,就地执行,什么都不返回(或者说返回None)
1 d = {} 2 d['name'] = 'Gumby' 3 d['age'] = 42 4 print(d) 5 return_value = d.clear() 6 print(d) 7 print(return_value)
结果:
1 {'name': 'Gumby', 'age': 42} 2 {} 3 None
2. copy
方法copy返回一个新字典,其包含的键-值对与原来的字典相同(该方法属于浅复制,因为值本身是原件,而非副本)。
1 x = {'username': 'admin', 'machines':['foo','bar','baz']} 2 y = x.copy() 3 y['username'] = 'mlh' 4 y['machines'].remove('bar') 5 print(y) 6 print(x) 7 结果: 8 {'username': 'mlh', 'machines': ['foo', 'baz']} 9 {'username': 'admin', 'machines': ['foo', 'baz']}
使用模块copy中的函数deepcopy,可以实现深复制,即同时复制值及所包含的值。
1 from copy import deepcopy 2 d = {} 3 d['names'] = ['Afriend','Bfriend'] 4 c = d.copy() 5 dc = deepcopy(d) 6 d['names'].append('Clive') 7 print(c) 8 print(dc) 9 结果: 10 {'names': ['Afriend', 'Bfriend', 'Clive']} 11 {'names': ['Afriend', 'Bfriend']}
3. fromkeys
该方法用于创建一个新字典,其中包含指定的键,且每个键对应的值都是None。
1 names1 = {}.fromkeys(['name','age']) 2 print(names1) 3 4 names2 = dict.fromkeys(['name', 'age']) 5 print(names2) 6 7 结果: 8 {'name': None, 'age': None} 9 {'name': None, 'age': None}
方法1是先创建一个空字典,再对其调用fromkeys创建另一个字典,略显多余。
方法2直接对dict调用方法fromkeys,更简洁实用(dict是左右字典所属的类型,故可以直接调用)。
也可以指定特定的值创建新字典。
1 names3 = dict.fromkeys(['name', 'age'], '(unknow)') 2 print(names3) 3 结果: 4 {'name': ['(unknow)', 40], 'age': ['(unknow)', 40]} 5 6 names4 = dict.fromkeys(['name', 'age'], ['unknow','25']) 7 print(names4) 8 结果: 9 {'name': ['unknow', '25'], 'age': ['unknow', '25']}
4. get - 访问字典(该方法可以访问字典中没有的项,则返回None,或者返回指定值)
1 d = {} 2 print(d.get('name')) 3 结果: 4 None 5 6 print(d.get('name', 'the key is not been found!')) 7 结果: 8 the key is not been found! 9 10 # 如果字典包含指定的键,get作用将于普通字典查找相同 11 d = {} 12 d['name'] = 'Eric' 13 print(d.get('name', 'the key is not been found!')) 14 结果: 15 Eric
使用方法get来访问 '数据库' 条目。
1 # 一个使用get()的简单数据库 2 # 在这里插入代码清单4-1中的数据库(字典people) 3 people = { 4 'Alice':{ 5 'phone': '2341', 6 'addr': 'Foo drive 23' 7 }, 8 'Beth':{ 9 'phone': '9102', 10 'addr': 'Bar street 43' 11 }, 12 'Cecil':{ 13 'phone': '3158', 14 'addr': 'Baz avenue 90' 15 } 16 17 } 18 19 labels = { 20 'phone': 'phone number', 21 'addr': 'adress' 22 } 23 24 name = input('Name: ') 25 26 # 要查找电话号码还是地址? 27 request = input('Phone number (p) or adress (a)?') 28 29 # 使用正确的键: 30 key = request # 如果request既不是p也不是a 31 if request == 'p': key = 'phone' 32 if request == 'a': key = 'addr' 33 34 # 使用get提供默认值 35 person = people.get(name, {}) 36 # print(person) 37 label = labels.get(key, key) 38 result = person.get(key, 'not availabe') 39 40 print("{}'s {} is {}!".format(name, label, result)) 41 42 结果: 43 Name: Alice 44 Phone number (p) or adress (a)?a 45 Alice's adress is Foo drive 23!
5. itmes
该方法返回一个包含所有字典项的列表,其中每个元素都为(key, value)的形式。字典项在列表中的排序不确定。
返回值属于一种名为 "字典视图" 的特殊类型,字典试图可用于迭代(迭代见第五章)。
1 d = {'title': 'Pyhton web site', 'url':'http://www.Python.org', 'spam': '0'} 2 print(d.items()) 3 结果: 4 dict_items([('title', 'Pyhton web site'), ('url', 'http://www.Python.org'), ('spam', '0')]) 5 6 length = len(d.items()) 7 print(length) 8 结果:3
如果需要将字典项复制到列表中,使用list函数即可。
1 print(list(d.items())) 2 结果: 3 [('title', 'Pyhton web site'), ('url', 'http://www.Python.org'), ('spam', '0')]
6. kyes - 该方法用于返回一个字典视图,其中包含指定字典中的键
1 d = {'title': 'Pyhton web site', 'url':'http://www.Python.org', 'spam': '0'} 2 print(d.keys()) 3 print(list(d.keys())) 4 结果: 5 dict_keys(['title', 'url', 'spam']) 6 ['title', 'url', 'spam']
7. pop - 该方法用于获取与指定键相关联的值,并将该键-值对从字典中删除
1 d = {'x':3,'y':6} 2 print(d.pop('x')) 3 print(d) 4 结果: 5 3 6 {'y': 6}
8. popitem
该方法用于随机弹出(删除该键-值对)一个字典项。因字典项的顺序是不确定的,无“最后一个元素”的概念,与list.pop弹出列表中最后一个元素不同。
1 d = {'title': 'Pyhton web site', 'url':'http://www.Python.org', 'spam': '0'} 2 print(d.popitem()) 3 print(d) 4 结果: 5 ('spam', '0') 6 {'title': 'Pyhton web site', 'url': 'http://www.Python.org'}
详见:模块collections中的OrderedDict类
9. stedefault(与方法get有点像)-该方法用于获取与指定键相关联的值
1)当指定键不存在时,在字典中添加指定的键-值对,并返回指定的值;
2)当指定键存在时,返回其值,并保持字典不变。
3)指定值可选,若没有指定,默认未None。
1 d = {} 2 print(d.setdefault('name')) 3 print(d) 4 结果: 5 None 6 {'name': None} 7 8 d = {} 9 print(d.setdefault('name', 'N/A')) 10 print(d) 11 结果: 12 N/A 13 {'name': 'N/A'}
1 # 指定的键存在时,返回指定值,并保持字典不变 2 d = {} 3 d['name'] = 'Gummy' 4 print(d.setdefault('name', 'N/A')) 5 print(d) 6 结果: 7 Gummy 8 {'name': 'Gummy'}
更多参见,模块collections中的defaultdict类。
10. update - 用一个字典中的项更新另一个字典
对于通过参数提供的字典,将其项添加到当前字典中;如果当前字典包含键相同的项,就替换它。
1 d = { 2 'title': 'python web site', 3 'url': 'http://www.python.org', 4 'changed': 'Mar 14 2016' 5 } 6 7 x = {'title': 'Python Language Website'} 8 # 观察该方法是否返回值 9 print(d.update(x)) 10 print(d) 11 结果: 12 None #由此可见并不返回值 13 {'title': 'Python Language Website', 'url': 'http://www.python.org', 'changed': 'Mar 14 2016'}
调用update时,可向它提供一个映射、一个由键-值对组成的序列(或其他可迭代对象)或关键字参数。
11. values
用于返回一个由字典中的值组成的字典视图。不同于keys,其返回的视图可能包含重复值。
1 d = {} 2 d[1] = 1 3 d[2] = 2 4 d[3] = 3 5 d[4] = 1 6 print(d.values()) 7 结果: 8 dict_values([1, 2, 3, 1])
章小结:
(1)关键词:映射、将字符串格式设置功能用于字典、字典方法
(2)新介绍函数:dict(seq) # 从键-值对、映射或关键字参数创建字典