
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人
2.5 字典
2.5.1 定义字典
字典通过一对花括号{}来定义。字典是由键值对构成的映射数据类型。只能通过字典的键去取对应的值,不能像字符串、列表和元组那样取切片:

2.5.2 更新字典内容
更新字典非常简单,直接通过字典的键(Key)赋值即可:

如果使用的键已经在字典中,则会把相应的值(Value)改掉;如果键不在字典中,则会向字典增加新的元素。
2.5.3 字典方法
➢ dict.fromkeys()。
fromkeys()方法用于创建具有相同默认值的字典:

➢ dict.keys()。
keys()方法返回字典所有的键:

➢ dict.values()。
values()方法返回字典所有的值:

➢ dict.items()。
items()方法返回字典键值对:

➢ dict.pop()。
pop()方法用于根据字典的键弹出元素:

➢ dict.get()。
get()方法用于通过字典的键取值。如果字典中有该键,则返回对应的值,否则返回None(None等同于其他语言里的Null,空值)。也可以指定返回值,如果键不在字典中,则返回指定的值。如下所示:


➢ dict.setdefault()。
setdefault()方法用于向字典添加新的元素。如果字典中已经有键,那么添加会失败,同时返回字典中键对应的值:

➢ dict.update()。
update()方法用于字典的合并:
