字典是一种映射类型,它将可以进行hash计算的key对象映射到任意类型的value对象上。字典是一种可变对象,目前Python3中仅有一种标准实现——dict。相较于list,在大量数据中查询时,dict速度更快,而dict使用的内存也会更多。
1. 创建字典
1 2 3 4 5 6 7 8 |
empty= {} # 构建空字典 empty_value= dict.fromkeys(['a', 'b', 'c']) # 构建值为None的字典,{'a': None, 'b': None, 'c': None} a= {'one': 1, 'two': 2, 'three': 3} # 常规构建 b= dict(one=1, two=2, three=3) # 使用**mapping构建 c= dict(zip(['one', 'two', 'three'], [1, 2, 3])) # 使用键值对构建 d= dict([('two', 2), ('one', 1), ('three', 3)]) # 使用键值对构建2 e= dict({'three': 3, 'one': 1, 'two': 2}) # 拷贝构建 a == b == c == d == e # True |
2. 访问字典元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
dict1= {'one': 1, 'two': 2, 'three': 3} dict1['one'] # 获取指定键的值,当键不存在时,触发KeyError异常 dict1.get('one', 1) # 获取指定键的值,当键不存在时,返回默认值 # 遍历字典的键1 for key in dict1: print(key, '=>', dict1[key]) # 遍历字典的键2 for key in dict1.keys(): print(key, '=>', dict1[key]) # 遍历字典的元素 for key, value in dict1.items(): print(key, '=>', value) # 遍历字典值 for value in dict1.values(): print(value) |
3. 更新字典
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
dict1= {'one': 1, 'two': 2, 'three': 3} # 当给指定键赋值时,若键存在,则其对应当值将被更新 dict1['two']= 3 print(dict1) # {'one': 1, 'two': 3, 'three': 3} # 当给指定键赋值时,若键不存在,则字典对象将添加该键值对 dict1['four']= 4 print(dict1) # {'one': 1, 'two': 3, 'three': 3, 'four': 4} # 使用setdefault(key[,default])来设置字典指定键的默认值,当该键已存在,则仅返回现有值 dict1.setdefault('five', 5) # 5 print(dict1) # {'one': 1, 'two': 3, 'three': 3, 'four': 4, 'five': 5} dict1.setdefault('five', 555) # 5 print(dict1) # {'one': 1, 'two': 3, 'three': 3, 'four': 4, 'five': 5} # 删除字典中指定键 dict1.pop('five') # 5 print(dict1) # {'one': 1, 'two': 3, 'three': 3, 'four': 4} dict1.pop('five', 555) # 555 print(dict1) # {'one': 1, 'two': 3, 'three': 3, 'four': 4} del dict1['four'] # {'one': 1, 'two': 3, 'three': 3} |
4. Python内置的字典操作符/函数
表达式 | 说明 | 示例 | 结果 |
x in dict | 判断对象x是否为dict的键 | a’ in {‘a’:1, ‘b’:2} | True |
for x in dict: | 遍历dict | for x in {‘a’:1, ‘b’:2}: print(x) | a b |
len(dict) | 计算dict的元素个数 | len({‘a’:1, ‘b’:2}) | 2 |
max(dict) | 计算dict中值最大的元素的键 | max({‘a’:1, ‘b’:2}) | b’ |
min(dict) | 计算dict中值最小的元素的键 | min({‘a’:1, ‘b’:2}) | a’ |
dict(mapping) | 使用现有映射类型创建字典 | dict(name=’aa’,age=12) | {‘name’: ‘aa’, ‘age’: 12} |
5. dict对象方法
方法名称 | 说明 |
len(d) | 返回字典元素个数 |
d[key] | 返回字典元素值 |
key [not] in d | 判断key是否在字典中 |
items() | 返回字典键值对集合 |
keys() | 返回字典键集合 |
values() | 返回字典值集合 |
setdefault(key[, default]) | 设置字典key的默认值,若存在返回现有值,否则返回default |
clear() | 情况字典中的元素 |
copy() | 拷贝字典(浅拷贝) |
dict.fromkeys(seq [, value]) | 使用seq序列元素作为键的集合,创建一个新的字典,所有字典的值为None或指定的value值 |
get(key [, default]) | 获取指定键的值,当字典中不存在该键时,返回default值 |
pop(key[, default ]) | 如果字典中存在键key,则删除它并返回其对应的值;否则返回default值 |
popitem() | 从字典中删除并返回任意一对键值对 |
setdefault(key[, default ]) | 当键key已存在于字典中时,返回其值;否则向字典中添加key,其对应的值为default或None |
update([other ]) | 使用另一个字典或键值对序列更新当前字典:若当前字典中存在这些键,则更新期对应的值;否则,向当前字典中添加这些新的键值对 |