字典 又被称为夫妻站(字典的元素由一个key+“:”+一个value组成)
字典注意事项:1.key只能是不可变序列(字符串,整数.......)
2.key不可以重复出现,但value却可以重复出现
3.字典的元素是无序的,它们的位置可以通过哈希函数计算其位置,然后输出
4.字典可以进行动态的伸缩
5.字典往往会浪费大量的内存,但其的查询速度很快
字典的创建(两种)
1.scores ={'张三’:98,'hello':100}
2.scores=dict('张三’:98,'hello':100)
3.空字典 scores={}
获取字典的元素
1.print(scores['张三’])
2.print(scores.get('张三’))
在输出字典中不存在的值时第一种会报错,第二种不会报错只会输出None
2.print(scores.get('999’,88))直接输出结果88,因为999不在字典中存在而且88为默认值
字典中增删改的操作 判断
1.用in 与not in 判断元素是否在字典中
2.删除使用del
del scores['张三']
3.清除用clear
scores.clear()
4.新增
scores[888]=777 (888为键,777为value)
字典的视图操作
'''用keys()获取所有键值 用value()获取所有值 用items()获取所有的键和值'''
scores={'hello':55,'world':66} keys=scores.keys() print(keys) print(list(keys))#以列表的形式输出 values=scores.values() print(values) print(list(values)) items=scores.items() print(items) print(list(items))
字典的遍历
scores={'hello':55,'world':66} for i in scores: print(i,scores.get(i),end='\t')
输出结果 hello 55 world 66
字典式的生成
'''用函数zip(),将两个以上序列打包'''
a=[555,66,999,55] b=['hh','kk','ll'] d={item.upper():price for item,price in zip(b,a)}#item:price是一个表达式写在for前面 print(d)
输出结果 {'HH': 555, 'KK': 66, 'LL': 999}