
上QQ阅读APP看书,第一时间看更新
3.9.2 字典操作
下面介绍字典元素的创建、访问、删除、修改、增加等相关操作。
1.字典的创建
(1)使用“=”将一个字典赋给一个变量。

(2)使用内建函数dict()。

(3)使用内建函数fromkeys()。

2.字典元素的访问
(1)keys()方法返回一个包含所有键的列表。

(2)has_key()方法检查字典中是否存在某一个键。

(3)values()方法返回一个包含所有值的列表。

(4)get()方法根据键返回值,如果不存在输入的键,返回None。

(5)items()方法返回一个(key,value)组成的元组。

(6)in运算用于判断某键是否在字典里,对于value值不适用。

(7)copy()方法复制字典。

3.字典元素的删除
(1)del()方法允许使用键从字典中删除元素。

(2)clear()方法清除字典中所有元素。

(3)pop()方法删除一个关键字并返回它的值。

4.字典元素的修改
update()方法类似于合并,把一个字典的键和值合并到另一个字典,覆盖相同键的值。

5.字典元素的增加

字典方法如表3-14所示。
表3-14 字典方法
