
2.5.2 字典的基本操作与方法
1.访问字典
列表和元组是通过下标来访问元素的,而字典不同,它通过键来访问对应的值。因为字典中的元素是无序的,每个元素的位置都不固定,所以字典也不能像列表和元组那样,采用切片的方式一次性访问多个元素。
Python访问字典元素的具体格式为:

其中,dictname表示字典变量的名字,key表示键名。注意,键必须是存在的,否则会报异常。
【例2-46】 通过键访问字典。

运算结果:

除了上面这种方式外,Python也推荐使用dict类型提供的get()方法来获取指定键对应的值。当指定的键不存在时,get()方法不会抛出异常。
get()方法的语法格式为:

其中,dictname表示字典变量的名字;key表示指定的键;default用于指定要查询的键不存在时,此方法返回的默认值,如果不手动指定,会返回None。
【例2-47】 通过get()方法访问字典。

运算结果:


本例中可以看到,当键不存在时,get()返回空值None,如果想明确地提示用户该键不存在,那么可以手动设置get()的第二个参数。
2.删除字典
和删除列表、元组一样,手动删除字典也可以使用del关键字。
【例2-48】 通过get()方法访问字典。

运算结果:

3.添加键值对
为字典添加新的键值对很简单,直接给不存在的key赋值即可,具体语法格式如下:

其中,dictname表示字典名称,key表示新的键,value表示新的值,只要是Python支持的数据类型都可以。
【例2-49】 添加字典键值对。

运算结果:

4.修改键值对
字典中键(key)的名字不能修改,只能修改值(value)。字典中各元素的键必须是唯一的,因此,如果新添加元素的键与已存在元素的键相同,那么键所对应的值就会被新的值替换掉,以此达到修改元素值的目的。
【例2-50】 添加字典键值对。

运算结果:

例中可以看到,字典中没有再添加一个{'第三名': 8.13}键值对,而是对原有键值对{'第三名':7.65}中的value做了修改。
5.删除键值对
如果要删除字典中的键值对,还可以使用del语句。
【例2-51】 使用del语句删除键值对。

运算结果:

6.判断字典中是否存在指定键值对
如果要判断字典中是否存在指定键值对,首先应判断字典中是否有对应的键。判断字典是否包含指定键值对的键,可以使用in或not in运算符。
需要指出的是,对于dict而言,in或not in运算符都是基于key来判断的。
通过in(或not in)运算符,可以很轻易地判断出现有字典中是否包含某个键,如果存在,由于通过键可以很轻易获取对应的值,因此很容易就能判断出字典中是否有指定的键值对。
【例2-52】 使用del语句删除键值对。


运算结果:

7.keys()、values()和items()方法
将这3个方法放在一起介绍,是因为它们都用来获取字典中的特定数据:
● keys()方法用于返回字典中的所有键(key);
● values()方法用于返回字典中所有键对应的值(value);
● items()方法用于返回字典中所有的键值对(key-value)。

2-8 获取字典中的特定数据
【例2-53】 获取字典中的键、值及键值对数据。

运算结果:

从例中可以发现,keys()、values()和items()返回值的类型分别为dict_keys、dict_values和dict_items,并不是常见的列表或者元组类型。如果需要列表类型等类型,则使用list()函数将它们返回的数据转换成列表或使用for in循环遍历它们的返回值。
【例2-54】 获取字典中的键、值及键值对数据后返回列表类型。

运算结果:

8.copy()方法
copy()方法是返回一个字典的副本,即返回一个具有相同键值对的新字典。
【例2-55】 字典的copy()方法应用。

运算结果:

从运行结果不难看出,对a增加新键值对,b不变;而修改a的某键值对中列表内的元素,b也会相应改变。
9.update()方法
update()方法可以使用一个字典所包含的键值对来更新己有的字典。在执行update()方法时,如果被更新的字典中已包含对应的键值对,那么原value会被覆盖;如果被更新的字典中不包含对应的键值对,则该键值对被添加进去。
【例2-56】 字典的update()方法应用。

运算结果:

从运行结果可以看出,由于被更新的字典中已包含key为“No.2”的键值对,因此更新时该键值对的value将被改写;而被更新的字典中不包含key为“No.5”的键值对,所以更新时会为原字典增加一个新的键值对。
10.pop()和popitem()方法
pop()和popitem()都用来删除字典中的键值对,不同的是,pop()用来删除指定的键值对,而popitem()用来随机删除一个键值对,它们的语法格式如下:

其中,dictname表示字典名称,key表示键。
【例2-57】 指定删除或随机删除。

运算结果:

11.setdefault()方法
setdefault()方法用来返回某个key对应的value,其语法格式如下:

说明,dictname表示字典名称,key表示键,defaultvalue表示默认值(可以不写,不写则为None)。
当指定的key不存在时,setdefault()会先为这个不存在的key设置一个默认的defaultvalue,然后再返回defaultvalue。也就是说,setdefault()方法总能返回指定key对应的value。
1)如果该key存在,那么直接返回该key对应的value;
2)如果该key不存在,那么先为该key设置默认的defaultvalue,然后再返回该key对应的defaultvalue。
【例2-58】 指定删除或随机删除。

运算结果:

从例中可以看出,key为“'石化'”存在时,直接返回该key对应的value,即0.7,而不会更改为setdefault()方法中的0.68。