字典
代码演示
'''
字典的创建方式
1.使用{}创建字典dic={key:value,key:value,....},使用[]创建列表list=[]
'''
dic={'张三':100,'王五':80,'李四':90}
print(dic)
#2.第二种创建字典的方式
dic=dict(name='jack',age=20)
print(dic)
#创建空字典
dic={}
print(dic)
查询字典的某个元素
#获取字典的元素
score={'张三':100,';李四':80,'王五':55}
#方法1:使用score[]
print(score['张三'])
#方法2,使用get(),
print(score.get('航司','不存在'))# '不存在'是当查找的元素不存在时,默认返回的值
获取所有的key-value
score={'张三':100,'李四':80,'王五':55}
#获取所有的key
keys=score.keys()
print(keys)
print(list(keys))#将所有的key组成的视图转成列表
#获取所有的value
values=score.values()
print(values)
print(list(values)) #将所有的value组成的视图转成列表
#获取所有的key-value
items=score.items()
print(items)
print(list(items)) #将所有的key-value组成的视图转成列表,列表包含n组元组```
'''
#字典元素的遍历
score={'张三':100,'李四':80,'王五':55}
for i in score:
print(i ,score[i])
print(i,score.get(i))
```python
```python
在这里插入代码片
```python
#字典的特点
#1.key不能重复,value可以重复,否则会出现值覆盖的现象
d={'name':'Jack','name':'lisa'}
print(d)
d={'name':'Jack','nameis':'Jack'}
print(d)
#2.字典中的元素是无序的,不能按照索引来插入value
#3.key必须是不可变的值
#4.字典可以根据需要动态的伸缩
#5.字典会浪费比较大的内存,是一种使用空间换时间的数据结构
使用两个list生成字典
items=['a','b','c']
prices=[1,2,3]
d={item:price for item,price in zip(items,prices)}#item是作为键,price是作为值 zip:打包,压缩
print(d)
print("----------------------------------------------------------------------")
#当key value个数不匹配时,以个数少的为准
items=['a','b','c']
prices=[1,2,3,4]
e={item:price for item,price in zip(items,prices)}
print(e)
#可以使用upper(),将key显示为大写
f={i.upper():p for i,p in zip(items,prices)}
print(f)
```python
在这里插入代码片
字典的增删改
#判断字典的元素是否存在
score={'张三':100,'李四':80,'王五':55}
print('张三'in score)
print('张三'not in score)
del score['张三'] #删除指定的key-value
print(score)
#score.clear() #删除字典中的所有元素
#print(score)
#新增
score['陈六']=98 #新增key-value
print(score)
#修改value
score['陈六']=101 #修改key-value
print(score)