系列文章目录
6.1 字典创建
字典,以对的形式存在;键-值对;无序;键不可以重复(当键重复时值会覆盖),但值可以重复;占用内存,用空间换时间。
#1.字典的创建方法一
scores={'张三':100,'李四':34,'王五':56}#使用花括号创建字典
print(scores)
scores={'张三':100,'李四':34,'王五':56,'张三':12}#键的重复
print(scores)
scores={'张三':100,'李四':34,'王五':56,'老刘':56}#值的重复
print(scores)
#2.使用内置函数创建字典
document=dict(name='jack',age=20)
print(document)
#3.创建空字典
docu={}
print(docu)
输出:
{‘张三’: 100, ‘李四’: 34, ‘王五’: 56}
{‘张三’: 12, ‘李四’: 34, ‘王五’: 56}
{‘张三’: 100, ‘李四’: 34, ‘王五’: 56, ‘老刘’: 56}
{‘name’: ‘jack’, ‘age’: 20}
{}
6.2 元素获取
scores={'张三':100,'李四':34,'王五':56}#使用花括号创建字典
print(scores['张三'])#第一种方式,值不存在时报错
print(scores.get('张三'))#使用get()方法,值不存在时默认输出None
print(scores.get('宋代斯莱'))#使用get()方法,值不存在时默认输出None
输出:
100
100
None
6.3 键的判断
scores={'张三':100,'李四':34,'王五':56}
print('张三' in scores)
输出:
True
6.4 元素删除
scores={'张三':100,'李四':34,'王五':56}
del scores['张三']
print(scores)
输出:
{‘李四’: 34, ‘王五’: 56}
6.5 元素添加
scores={'张三':100,'李四':34,'王五':56}
scores['老刘']=90
print(scores)
输出:
T{‘张三’: 100, ‘李四’: 34, ‘王五’: 56, ‘老刘’: 90}
6.6 元素修改
scores={'张三':100,'李四':34,'王五':56}
scores['老刘']=40.2
print(scores)
输出:
{‘张三’: 100, ‘李四’: 34, ‘王五’: 56, ‘老刘’: 40.2}
6.7 字典清空
scores={'张三':100,'李四':34,'王五':56}
scores.clear()
print(scores)
输出:
{ }
6.8 字典视图获取
scores={'张三':100,'李四':34,'王五':56}
print(scores.keys())#获取字典中的键
print(list(scores.keys()))#获取字典中的键并将其转换为列表
print(scores.values())#获取字典中的值
print(list(scores.values()))#获取字典中的值并将其转换为列表
print(scores.items())#获取所有的键-值对
print(list(scores.items()))#将所有的键值对转换为列表下的元组
输出:
dict_keys([‘张三’, ‘李四’, ‘王五’])
[‘张三’, ‘李四’, ‘王五’]
dict_values([100, 34, 56])
[100, 34, 56]
dict_items([(‘张三’, 100), (‘李四’, 34), (‘王五’, 56)])
[(‘张三’, 100), (‘李四’, 34), (‘王五’, 56)]
6.9 元素遍历
scores={'张三':100,'李四':34,'王五':56}
for item in scores:#获取字典中键
print(item,end='\t')
print('\n')
for item in scores:#获取字典中值
print(scores[item],end='\t')#[]法
print(scores.get(item),end='\t')#get()法
输出:
张三 李四 王五100 100 34 34 56 56
6.10 字典生成式
lst1=['name','age','home','borthday']
lst2=['Jack','18','Beijing','1999.5.19']
print(list(zip(lst1,lst2)))#内置函数zip(),多余不打包
d={shuxin:texin for shuxin,texin in zip(lst1,lst2)}#字典生成式
print(d)
输出:
[(‘name’, ‘Jack’), (‘age’, ‘18’), (‘home’, ‘Beijing’), (‘borthday’, ‘1999.5.19’)]
{‘name’: ‘Jack’, ‘age’: ‘18’, ‘home’: ‘Beijing’, ‘borthday’: ‘1999.5.19’}