14 字典-Dict
14.1 基本介绍
- 5. 数据结构 — Python 3.12.7 文档
- 字典Dict,完整的单词是 Dictionary,也是一种常用的 Python 数据类型,其它语言可能把字典称为联合内存或联合数组;
- 字典是一种映射类型,非常适合处理通过 x 査询 y 的需求,这里的 x 我们称为 Key(键/关键字),这里的 y 我们称为Value(值),即 Key-Value的映射关系。
14.2 定义
-
创建一个字典,只要把逗号分隔的不同的元素用
{}
括起来即可,存储的元素是一个个键值对;dict_a = {key:value, key:value, key:value...}
14.3 使用
-
语法:
字典名[key]
14.4 注意事项和使用细节
-
字典的Key(关键字)通常是字符串或数字,Value可以是任意数据类型;
-
字典不支持索引;
-
因为字典不支持索引,所以对字典进行遍历不支持
while
,只支持for
。若直接遍历字典,取出的只有Key;-
遍历方式1:
dict_color = {'color1': 'red', 'color2': 'green', 'color3': 'blue', 'color4': 'yellow', 'color5': 'white', 'color6': 'black'} for color in dict_color: print(f"Key:{color} - Value:{dict_color[color]}") # Key:color1 - Value:red # Key:color2 - Value:green # Key:color3 - Value:blue # Key:color4 - Value:yellow # Key:color5 - Value:white # Key:color6 - Value:black
-
遍历方式2:
dict_color = {'color1': 'red', 'color2': 'green', 'color3': 'blue', 'color4': 'yellow', 'color5': 'white', 'color6': 'black'} for color in dict_color.values(): print(f"Value:{color}") # Value:red # Value:green # Value:blue # Value:yellow # Value:white # Value:black
-
遍历方式3:
dict_color = {'color1': 'red', 'color2': 'green', 'color3': 'blue', 'color4': 'yellow', 'color5': 'white', 'color6': 'black'} for k, v in dict_color.items(): print(f"Key:{k} - Value:{v}") # Key:color1 - Value:red # Key:color2 - Value:green # Key:color3 - Value:blue # Key:color4 - Value:yellow # Key:color5 - Value:white # Key:color6 - Value:black
-
-
创建空字典可以通过
{}
,或者dict()
:dict1 = {} # 或 dict1 = dict()
-
字典的 Key 必须是唯一的,如果指定了多个相同的 Key,那么后面的键值对会覆盖前面的。
14.5 常用操作
函数 | 作用 |
---|---|
len(dict) | 返回字典的键值对个数 |
dict[key] | 如果 Key 存在,返回 dict 中以 Key为键的项 如果 Key 不存在,则会引发 KeyError |
dict[key] = value | 如果 Key 存在,则是修改对应的 Value 如果 Key 不存在,则增加 Key - Value |
del dict[key] | 如果 Key 存在,移除对应的键值对 如果 Key 不存在,则会引发 KeyError |
dict.pop(key[,default]) | 如果 Key 存在,则将其移除并返回其值,否则返回default 如果 Key 不存在,则会引发 KeyError |
dict.keys() | 返回字典素有的Key |
key in dict | 如果 Key 存在,则返回 True,否则返回 False |
dict.clear() | 移除字典中的所有元素 |
14.6 字典生成式
-
内置函数
zip()
可以将可迭代的对象作为参数,将对象中对应的元素打包成一个元组,返回由这些元组组成的列表; -
语法:
{字典Key的表达式: 字典Value的表达式 for 表示Key的变量,表示Value的变量 in zip(可迭代对象, 可迭代对象)}
-
例:
authors = ["曹雪芹", "罗贯中", "吴承恩", "施耐庵"] books = ["红楼梦", "三国演义", "西游记", "水浒传"] dict_ = {book: author for book, author in zip(books, authors)} for k, v in dict_.items(): print(f"key: {k} - value: {v}") # key: 红楼梦 - value: 曹雪芹 # key: 三国演义 - value: 罗贯中 # key: 西游记 - value: 吴承恩 # key: 水浒传 - value: 施耐庵