【零基础Python专题(源码版)】篇章3·字典dict
下面列举的Python的字典基础知识(三引号成对儿注释的内容为一个小知识点),可以直接在Pycharm运行学习:
#字典
#存储无序
#字典的创建
'''# 使用{}创建
scores={"张三":100,"李四":90,"王五":95}
print(scores)
# 使用内置函数dict()创建
student=dict(name="张三",age=20)
print(student)'''
#获取字典元素
# 使用[]
'''scores={"张三":100,"李四":90,"王五":95}
print(scores["张三"])
# 使用get()方法
print(scores.get("张三"))
print(scores.get("小明",95))#查找不存在时输出固定值'''
#字典的增删改
'''# 增
scores={"张三":100,"李四":90,"王五":95}
scores["小红"]=95
print(scores)
# 删
del scores["张三"] #scores.clear()清空字典
print(scores)
# 改
scores["李四"]=95
print(scores)'''
#获取字典视图
'''# 获取key值
scores={"张三":100,"李四":90,"王五":95}
keys=scores.keys()
print(keys)
list_keys=list(keys)
# 获取value值
values=scores.values()
print(values)
list_values=list(values)
# 获取key-value键值对儿
items=scores.items()
print(list(items))'''
#字典的遍历
'''scores={"张三":100,"李四":90,"王五":95}
for item in scores:
print(item,scores[item],scores.get(item))'''
#字典生成式
'''items=["Fruits","Books","Others"]
prices=[90,80,70]
d={item.upper():price for item,price in zip(items,prices)}
print(d)'''