python6 字典
字典
字典是Python内置的数据结构之一,是一个可变序列【和列表一样】
键值对方式存储,字典是一个无序的序列
类型为 : dict
底层貌似是用hash函数进行计算的
创建
-
常用 花括号 直接生成 / 用内置函数dict()
-
# 作者:咸瑜 # 代码时间:2022/11/9 20:18 # 创建 test = {'时间': 2021, '年龄': 18, '身高': '1m63'} print(test) print(type(test)) test = dict(时间=2022, 年龄=19, 身高='1m65') print(test) print(type(test)) # {'时间': 2021, '年龄': 18, '身高': '1m63'} # <class 'dict'> # {'时间': 2022, '年龄': 19, '身高': '1m65'} # <class 'dict'>
-
获取
- ['key'],如果不存在key,抛出keyError 异常
- get('key',默认值) 方法,如果不存在key,返回None
例:
# 作者:咸瑜
# 代码时间:2022/11/9 20:18
# 获取
test = dict(时间=2022, 年龄=19, 身高='1m65')
print(test['年龄'])
print(test['?']) #keyError异常:'?'
test = dict(时间=2022, 年龄=19, 身高='1m65')
print(test.get('年龄'))
print(test.get('?')) #None
print(test.get('?', "默认值")) # 默认值
判断-key
in 和 not in 用于判断 key 是否存在 字典中
例:
# 作者:咸瑜
# 代码时间:2022/11/9 20:18
test = {"1": '一', "2": "二"}
print('2' in test)#True
print('2' not in test)#false
print('3' in test)#false
print('3' not in test)#True
删除
del dict['Key'] 是删除字典中指定key的键值对
clear() 函数是删除字典中全部元素
增添元素
dict[Key] = 'Value'
删除 和 添加 例子:
# 作者:咸瑜
# 代码时间:2022/11/9 20:18
test = {"1": '一', "2": "二"}
# 删除1
del test['1']
print(test)
# 清空字典元素
test.clear()
print(test)
# 添加元素
test['姓名'] = '咸瑜'
print(test)
# {'2': '二'}
# {}
# {'姓名': '咸瑜'}
获取字典视图
- keys 获取所有键
- values 获取所有值
- items 获取所有键-值
test = {"1": '一', "2": "二"}
print(test.keys(),type(test.keys()))
print(test.values(),type(test.values()))
print(test.items(),type(test.items()))
# dict_keys(['1', '2']) <class 'dict_keys'>
# dict_values(['一', '二']) <class 'dict_values'>
# dict_items([('1', '一'), ('2', '二')]) <class 'dict_items'>
# 虽然是dict_keys、dict_values、dict_items 类型,但是可以转换成list类型
test = {"1": '一', "2": "二"}
print(list(test.keys())) # ['1', '2']
print(list(test.values())) # ['一', '二']
print(list(test.items())) # [('1', '一'), ('2', '二')]
## 遍历
# 遍历
test = {"1": '一', "2": "二"}
for item in test:
print(item) # item 就是键
print(test[item]) # 值
print(test.get(item)) # 值
# 运行结果:
# 1
# 一
# 一
# 2
# 二
# 二
字典的特点
- 所有元素都是键值对,key不能重复,value可以重复,如果key重复,按最后一个为准.
- 字典中的元素是无序的
- key是必须不可改变的,只能删除
- 可以根据需要动态伸缩
- 会浪费大量内存,是一种使用空间换时间的数据结构
字典生成式
用 zip函数把字典生成为 可迭代元素
# 作者:咸瑜
# 代码时间:2022/11/9
# 字典生成式
# 列表
keys = ["Name", "Age", "Vocation"]
values = ["咸瑜", 18, "学生"]
# 返回值:地址,类型: zip
print(zip(keys, values), type(zip(keys, values)))
# 把 keys 和 values 结合成字典:
newDict = {key: value for key, value in zip(keys, values)}
print(newDict)
# 如果列表不对称:那么就按顺序,生成最少(下面生成3个,因为最少元素个数为3)
keys = ["Name", "Age", "Vocation", "surplus"]
values = ["咸瑜", 18, "学生"]
newDict = {key: value for key, value in zip(keys, values)}
print(newDict)
# 可以和list互相转换
print(list(zip(keys, values)))
完。
本文来自博客园,作者:咸瑜,转载请注明原文链接:https://www.cnblogs.com/bi-hu/p/16875831.html