Python-数据类型:字典
0 前言
1 字典的重要特性
字典是键(key
)值(value
)成对的无序可变序列,其中键不可重复不可变,值可重复可变
注意,从Python3.6开始,字典变为有序序列,但需要显式转换为list类型才能有序读取。
1.1 创建空字典
x = {} #空字典
x = dict() # 空字典
1.2 创建初始化key的字典
提供所有key组成的序列和所有value的初值,value的初值默认为None
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
>>>Dictionary : {'age': None, 'name': None, 'sex': None}
dict = dict.fromkeys(seq, 10)
>>>Dictionary : {'age': 10, 'name': 10, 'sex': 10}
1.3 完整创建字典
x = {'key1':10, 'key2':20, 'key3':30}
x = dict(key1 = 10, key2 = 20, key3 = 30)
x = dict([('key1', 10), ('key2', 20), ('key3', 30)])
x = dict(zip(['key1', 'key2', 'key3'], [10, 20, 30]))
2 字典的方法
- 改变自身的方法
self=Dictionary类 | 说明 |
---|---|
self[key] -> valueself[key] -> Exceptionself[key] = value | 按键读取或写入对应的值 键不存在时返回 KeyError |
self.get(key) -> valueself.get(key) -> None self.get(key) = value | 按键读取或写入对应的值 键不存在时返回 None |
self.pop(key) | 删除指定键值对 |
self.clear() | 清空字典 |
self.update(newdict) | 合并一个字典,同键的值覆盖 |
- 不改变自身的方法
self=Dictionary类 | 说明 |
---|---|
self.keys() -> list | 返回所有键组成的列表 |
=self.values() -> list | 返回所有值组成的列表 |
=self.items() -> list of tuple | 返回(键,值)元组组成的列表 |
2.2 访问字典 get keys values
x = {'key1':10, 'key2':20, 'key3':30}
x.get('key1') = 10
x.get('key4', '不存在') # 输出‘不存在’
y = [x.keys()] # y = ['key1', 'key2', 'key3']
y = [x.values()] # y = [10, 20, 30]
2.3 修改字典 update pop clear
x = {'key1':10, 'key2':20, 'key3':30}
x['key1'] = 15 # 修改
x.update({'key4': 40}) # 添加或覆盖
x.pop('key2') # 删除
clear(x) # 清除
2.4 字典解包 items keys values
x = {'key1':10, 'key2':20, 'key3':30}
a1,a2,a3 = x.items() # 键值对解包
b1,b2,b3 = x.keys() # 键解包
c1,c2,c3 = x.values() # 值解包
结果:
a1 = ('key1', 10)
a2 = ('key2', 20)
a3 = ('key3', 30
b1 = 'key1'
b2 = 'key2'
b3 = 'key3'
c1 = 10
c2 = 20
c3 = 30
3 字典的有序性
从Python3.6开始,字典变为有序序列,但需要显式转换为list类型才能有序读取。
x = {'a':10, 'b':20, 'c':30}
b = list(x.items()) # b = [('a',10), ('b',20), ('c',30)] 有序列表
b = list(x.keys()) # b = ['a','b','c'] 有序列表
b = list(x.values()) # b = [1,2,3] 有序列表