前言
前面我们学习了 Python学习篇(一) 新建Python文件 Python学习篇(二) Python中的变量和数据类型 Python学习篇(三) Python中的运算符 Python学习篇(四) Python中的分支结构 Python学习篇(五) Python中的循环 Python学习篇(六) Python中的列表 今天我们继续学习Python中的字典,并了解字典的用途,及相关操作,就是增删改查。
一、什么是字典?
 
二、字典的创建
 
'''使用{}创建'''
scores={'张三':100,'李四':98,'王五':45,}
'''使用dict创建'''
student=dict(name='jack',age=20)
print(scores)
print(student)
'''空字典'''
d={}
print(d)
三、字典的常用操作
3.1字典中元素的获取
 
'''使用{}创建'''
scores={'张三':100,'李四':98,'王五':45,}
print(scores['张三'])
print(scores.get('张三'))
3.2字典中元素的获取
 
scores={'张三':100,'李四':98,'王五':45,}
'''key的判断'''
print('张三' in scores)
print('张三' not in scores)
del scores['张三']
print(scores)
scores['jack']=90
print(scores)
'''修改'''
scores['jack']=100
print(scores)
四、获取视图的三个方法
 
scores={'张三':100,'李四':98,'王五':45,}
'''获取所有的key'''
keys=scores.keys()
print(keys)
print(type(keys))
print(list(keys))
'''获取所有的values'''
values=scores.values()
print(values)
print(type(values))
print(list(values))
'''获取所有的items'''
items=scores.items()
print(items)
print(type(items))
print(list(items))
五、字典的遍历
 
scores={'张三':100,'李四':98,'王五':45,}
for item in scores:
print(item,scores[item],scores.get(item))
六、字典的特点
  查找速度很快,但是浪费较多内存空间

七、字典生成式
  
items=['Fruits','Books','Others']
prices=['96','78','86']
d={item:price for item,price in zip(items,prices) }
print(d)
总结

|