Python基础 第四章 字典(2)字典方法&章小结

时间:2023-03-09 04:46:14
Python基础 第四章 字典(2)字典方法&章小结

1. clear

方法clear删除所有的字典项,就地执行,什么都不返回(或者说返回None)

 d = {}
d['name'] = 'Gumby'
d['age'] = 42
print(d)
return_value = d.clear()
print(d)
print(return_value)

结果:

 {'name': 'Gumby', 'age': 42}
{}
None

2. copy

方法copy返回一个新字典,其包含的键-值对与原来的字典相同(该方法属于浅复制,因为值本身是原件,而非副本)。

 x = {'username': 'admin', 'machines':['foo','bar','baz']}
y = x.copy()
y['username'] = 'mlh'
y['machines'].remove('bar')
print(y)
print(x)
结果:
{'username': 'mlh', 'machines': ['foo', 'baz']}
{'username': 'admin', 'machines': ['foo', 'baz']}

使用模块copy中的函数deepcopy,可以实现深复制,即同时复制值及所包含的值。

 from copy import deepcopy
d = {}
d['names'] = ['Afriend','Bfriend']
c = d.copy()
dc = deepcopy(d)
d['names'].append('Clive')
print(c)
print(dc)
结果:
{'names': ['Afriend', 'Bfriend', 'Clive']}
{'names': ['Afriend', 'Bfriend']}

3. fromkeys

该方法用于创建一个新字典,其中包含指定的键,且每个键对应的值都是None。

 names1 = {}.fromkeys(['name','age'])
print(names1) names2 = dict.fromkeys(['name', 'age'])
print(names2) 结果:
{'name': None, 'age': None}
{'name': None, 'age': None}

方法1是先创建一个空字典,再对其调用fromkeys创建另一个字典,略显多余。

方法2直接对dict调用方法fromkeys,更简洁实用(dict是左右字典所属的类型,故可以直接调用)。

也可以指定特定的值创建新字典。

 names3 = dict.fromkeys(['name', 'age'], '(unknow)')
print(names3)
结果:
{'name': ['(unknow)', 40], 'age': ['(unknow)', 40]} names4 = dict.fromkeys(['name', 'age'], ['unknow',''])
print(names4)
结果:
{'name': ['unknow', ''], 'age': ['unknow', '']}

4. get - 访问字典(该方法可以访问字典中没有的项,则返回None,或者返回指定值)

 d = {}
print(d.get('name'))
结果:
None print(d.get('name', 'the key is not been found!'))
结果:
the key is not been found! # 如果字典包含指定的键,get作用将于普通字典查找相同
d = {}
d['name'] = 'Eric'
print(d.get('name', 'the key is not been found!'))
结果:
Eric

使用方法get来访问 '数据库' 条目。

 # 一个使用get()的简单数据库
# 在这里插入代码清单4-1中的数据库(字典people)
people = {
'Alice':{
'phone': '',
'addr': 'Foo drive 23'
},
'Beth':{
'phone': '',
'addr': 'Bar street 43'
},
'Cecil':{
'phone': '',
'addr': 'Baz avenue 90'
} } labels = {
'phone': 'phone number',
'addr': 'adress'
} name = input('Name: ') # 要查找电话号码还是地址?
request = input('Phone number (p) or adress (a)?') # 使用正确的键:
key = request # 如果request既不是p也不是a
if request == 'p': key = 'phone'
if request == 'a': key = 'addr' # 使用get提供默认值
person = people.get(name, {})
# print(person)
label = labels.get(key, key)
result = person.get(key, 'not availabe') print("{}'s {} is {}!".format(name, label, result)) 结果:
Name: Alice
Phone number (p) or adress (a)?a
Alice's adress is Foo drive 23!

5. itmes

该方法返回一个包含所有字典项的列表,其中每个元素都为(key, value)的形式。字典项在列表中的排序不确定。

返回值属于一种名为 "字典视图" 的特殊类型,字典试图可用于迭代(迭代见第五章)。

 d = {'title': 'Pyhton web site', 'url':'http://www.Python.org', 'spam': ''}
print(d.items())
结果:
dict_items([('title', 'Pyhton web site'), ('url', 'http://www.Python.org'), ('spam', '')]) length = len(d.items())
print(length)
结果:3

如果需要将字典项复制到列表中,使用list函数即可。

 print(list(d.items()))
结果:
[('title', 'Pyhton web site'), ('url', 'http://www.Python.org'), ('spam', '')]

6. kyes - 该方法用于返回一个字典视图,其中包含指定字典中的键

 d = {'title': 'Pyhton web site', 'url':'http://www.Python.org', 'spam': ''}
print(d.keys())
print(list(d.keys()))
结果:
dict_keys(['title', 'url', 'spam'])
['title', 'url', 'spam']

7. pop - 该方法用于获取与指定键相关联的值,并将该键-值对从字典中删除

 d = {'x':3,'y':6}
print(d.pop('x'))
print(d)
结果:
3
{'y': 6}

8. popitem

该方法用于随机弹出(删除该键-值对)一个字典项。因字典项的顺序是不确定的,无“最后一个元素”的概念,与list.pop弹出列表中最后一个元素不同。

 d = {'title': 'Pyhton web site', 'url':'http://www.Python.org', 'spam': ''}
print(d.popitem())
print(d)
结果:
('spam', '')
{'title': 'Pyhton web site', 'url': 'http://www.Python.org'}

详见:模块collections中的OrderedDict类

9. stedefault(与方法get有点像)-该方法用于获取与指定键相关联的值

1)当指定键不存在时,在字典中添加指定的键-值对,并返回指定的值;

2)当指定键存在时,返回其值,并保持字典不变。

3)指定值可选,若没有指定,默认未None。

 d = {}
print(d.setdefault('name'))
print(d)
结果:
None
{'name': None} d = {}
print(d.setdefault('name', 'N/A'))
print(d)
结果:
N/A
{'name': 'N/A'}
 # 指定的键存在时,返回指定值,并保持字典不变
d = {}
d['name'] = 'Gummy'
print(d.setdefault('name', 'N/A'))
print(d)
结果:
Gummy
{'name': 'Gummy'}

更多参见,模块collections中的defaultdict类。

10. update - 用一个字典中的项更新另一个字典

对于通过参数提供的字典,将其项添加到当前字典中;如果当前字典包含键相同的项,就替换它。

 d = {
'title': 'python web site',
'url': 'http://www.python.org',
'changed': 'Mar 14 2016'
} x = {'title': 'Python Language Website'}
# 观察该方法是否返回值
print(d.update(x))
print(d)
结果:
None #由此可见并不返回值
{'title': 'Python Language Website', 'url': 'http://www.python.org', 'changed': 'Mar 14 2016'}

调用update时,可向它提供一个映射、一个由键-值对组成的序列(或其他可迭代对象)或关键字参数。

11. values

用于返回一个由字典中的值组成的字典视图。不同于keys,其返回的视图可能包含重复值。

 d = {}
d[1] = 1
d[2] = 2
d[3] = 3
d[4] = 1
print(d.values())
结果:
dict_values([1, 2, 3, 1])

章小结:

(1)关键词:映射、将字符串格式设置功能用于字典、字典方法

(2)新介绍函数:dict(seq) # 从键-值对、映射或关键字参数创建字典