前言
python学习笔记day3 (仅供学习使用)
一、什么是字典
python内置的数据结构之一,与列表一样是个可变序列
以键值对的方式存储数据,字典是一个无序序列
二、字典的创建
1.使用花括号{}
'''使用{}创建字典'''
scores={'张三':100,'李四':98,'王五':45}
print(scores)
print(type(scores))
'''空字典'''
d={}
print(d)
2.使用内置函数dict()
student=dict(name='jack',age=20)
print(student)
三、字典中元素的获取
'''获取字典的元素'''
scores={'张三':100,'李四':98,'王五':45}
'''第一种方式,使用[]'''
print(scores['张三'])
#print(scores['陈六']) #KeyError: '陈六'
'''第二种方式,使用get()方法'''
print(scores.get('张三'))
print(scores.get('陈六')) #None
print(scores.get('麻七',99)) #99是在查找'麻七'所对的value不存在时,提供的一个默认值
运行:
100
100
None
99
四、字典的增删改
'''key的判断'''
scores={'张三':100,'李四':98,'王五':45}
print('张三' in scores)
print('张三' not in scores)
del scores['张三'] #删除指定的key-value对
#scores.clear() #清空字典的元素
print(scores)
scores['陈六']=98 #新增元素
print(scores)
scores['陈六']=100 #修改元素
print(scores)
运行:
True
False
{'李四': 98, '王五': 45}
{'李四': 98, '王五': 45, '陈六': 98}
{'李四': 98, '王五': 45, '陈六': 100}
五、字典的视图操作
scores={'张三':100,'李四':98,'王五':45}
#获取所有的key
keys=scores.keys()
print(keys)
print(type(keys))
print(list(keys)) #将所有的key组成的视图转成列表
#获取所有的value
values=scores.values()
print(values)
print(type(values))
print(list(values))
#获取所有的key-value对
items=scores.items()
print(items)
print(list(items)) #转换之后的列表元素是由元组组成
运行:
dict_keys(['张三', '李四', '王五'])
<class 'dict_keys'>
['张三', '李四', '王五']
dict_values([100, 98, 45])
<class 'dict_values'>
[100, 98, 45]
dict_items([('张三', 100), ('李四', 98), ('王五', 45)])
[('张三', 100), ('李四', 98), ('王五', 45)]
六、字典元素的遍历
scores={'张三':100,'李四':98,'王五':45}
#字典元素的遍历
for item in scores:
print(item,scores[item],scores.get(item))
运行:
张三 100 100
李四 98 98
王五 45 45
七、字典的特点
八、字典生成式
items=['Fruits','Books','Others']
prices=[96,78,85,100,120]
#upper()是将item变成大写。
d={item.upper():price for item ,price in zip(items,prices) }
print(d)
运行:
{'FRUITS': 96, 'BOOKS': 78, 'OTHERS': 85}