【Python基础语法04】数据结构之字典
程序员文章站
2024-01-27 14:22:46
...
前言
上一讲分享了数据结构中的元组 tuple,本讲将走进字典 dict。采用 Q & A 的形式讲解几点思考并采用脑图的形式进行总结。
Q1:什么是 dict
dict 是存储数据的容器之一,是无序的可变映射容器 map;由若干组键值对 {key : value} 构成,用花括号标识,每对键值对之间用逗号隔开,key 与 value 之间用冒号隔开。key 是唯一的,不可变;value 是可变的。
>>> dic = {'name':'chen','score':100,'age':18}
>>> print(dic,type(dic))
{'name': 'chen', 'score': 100, 'age': 18} <class 'dict'>
Q2:为什么设置 dict
list 与 tuple 都是序列 seq,这里的有序是指先后有顺序,即索引 index;seq 缺少一对一的关联属性,而 map 恰恰弥补了这一点。
Q3:如何访问 dict 中的元素
seq 中借助 index, slice, stride 实现,map 中借助 key 即可。此外,dict 还有一些内置方法可以快捷的访问 dict 的 key, value, (key, value)。注意嵌套 dict 的重复指向 key, 这与后期 Numpy 中的多维数组访问类似。
>>> dic = {'name':'chen','score':100,'age':18,'other':{'height':188}}
>>> print(dic['name'])
chen
>>> print(dic['other']['height'])
188
下表展示了访问 dict 的常用内置方法。
方法 | 描述 | 实例 |
---|---|---|
dic.get(key) | 返回 key 的值 | >>> dic = {‘name’:‘chen’,‘score’:100,‘age’:18,‘other’:{‘height’:188}} >>> print(dic.get(‘name’)) chen |
dic.keys() | 返回 dic 的所有 key | >>> dic = {‘name’:‘chen’,‘score’:100,‘age’:18,‘other’:{‘height’:188}} >>> print(dic.keys()) dict_keys([‘name’, ‘score’, ‘age’, ‘other’]) |
dic.values() | 返回 dic 的所有 value | >>> dic = {‘name’:‘chen’,‘score’:100,‘age’:18,‘other’:{‘height’:188}} >>> print(dic.values()) dict_values([‘chen’, 100, 18, {‘height’: 188}]) |
dic.items() | 返回 dic 的所有元素 | >>> dic = {‘name’:‘chen’,‘score’:100,‘age’:18,‘other’:{‘height’:188}} >>> print(dic.items()) dict_items([(‘name’, ‘chen’), (‘score’, 100), (‘age’, 18), (‘other’, {‘height’: 188})]) |
Q4:如何修改 dict
与 seq 类似,修改 list 也涉及到一些常用的内置函数与方法。内置函数与 seq 类似,即 del, len(dict), in等。
下表列举了常用的内置方法。
方法 | 描述 | 实例 |
---|---|---|
dic.clear() | 清空 dic | >>> dic = {‘name’:‘chen’,‘score’:100,‘age’:18,‘other’:{‘height’:188}} >>> print(dic.clear()) None |
dic.pop(key) | 移除 dic 中 key 对应的值 | >>> dic = {‘name’:‘chen’,‘score’:100,‘age’:18,‘other’:{‘height’:188}} >>> print(dic.pop(‘age’)) 18 >>> print(dic) {‘name’: ‘chen’, ‘score’: 100, ‘other’: {‘height’: 188}} |
dic.copy() | 复制 dic | >>> dic = {‘name’:‘chen’,‘score’:100,‘age’:18,‘other’:{‘height’:188}} >>> dic2 = dic.copy() >>> print(dic2) {‘name’: ‘chen’, ‘score’: 100, ‘age’: 18, ‘other’: {‘height’: 188}} |
dict.fromkeys(seq) | 将 seq 元素当作 key 创建 dict | >>> seq = (‘name’,‘score’,‘age’) >>> dic = dict.fromkeys(seq) >>> print(dic) {‘name’: None, ‘score’: None, ‘age’: None} >>> dic = dict.fromkeys(seq,10) >>> print(dic) {‘name’: 10, ‘score’: 10, ‘age’: 10} |
dic1.update(dic2) | 将 dic2 更新到 dic1 中 | >>> dic1 = {“a”:1, “b”:2} >>> dic2 = {“c”:3, “d”:4} >>> dic1.update(dic2) >>> print(dic1,dic2) {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4} {‘c’: 3, ‘d’: 4} |