3.2 字典
1.如果没有字典
1)定义一个变量保存一个学生的信息
# 使用列表
stu1 = ['小明',28,'男',170,63,80,89,99]
print(stu1[0],stu1[-1]) #小明 99
# 使用字典
stu2 ={'name':'小明','age':28,'性别':'男','身高':170,'体重':63,'语文':80,'数学':89,'英语':99}
print(stu2['name'],stu2['英语']) #小明 99
2)字典和列表的选择
如果同时保存的多个意义相同的数据(都是名字、年龄、学生等)就使用列表;
如果同时保存的多个意义不同的数据就使用字典。
2.什么是字典(dict)
1)字典是容器型数据类型,将{}作为容器的标志,里面多个键值对用逗号隔开:{键1:值1,键2:值2,键3:值3…}
2)字典是可变的(支持增删改);字典是无需的(不支持下标操作)
3)字典的要求:字典的元素是键值对
键的要求:a.键必须是不可变类型的数据(一般使用字符串) b.键是唯一的
值的要求:没有要求
# 空字典
dict1 = {}
print(len(dict1),type(dict1)) #0 <class 'dict'>
3.字典是无序的
print({'a':10,'b':20} == {'b':20,'a':10}) #True
键必须是不可变类型的数据(字符串、布尔、空值、数字、元组)
dict2 = {10:20,'ab':30,(10,20):40}
print(dict2) #{10: 20, 'ab': 30, (10, 20): 40}
# dict2 = {10:20,'ab':30,[10,20]:40}
# print(dict2) # unhashable type: 'list'
键是唯一的
dict3 = {'a':100,'b':20,'a':30}
print(dict3) #{'a': 30, 'b': 20}
3.2.1 字典的查操作
1.查单个 - 获取字典某一个键对应的值
1)字典[键] - 获取字典中指定键对应的值, 如果键不存在会报错
2)字典.get(键) - 获取字典中指定键对应的值;如果键不存在不会报错,并且返回None
字典.get(键, 默认值) - 获取字典中指定键对应的值;如果键不存在不会报错,并且返回默认值
dog = {'name': '旺财', 'age': 3, 'breed': '土狗', 'gender': '母狗'}
print(dog['name'], dog['gender']) #旺财 母狗
print(dog.get('name'), dog.get('age')) #旺财 3
# print(dog['color']) # KeyError: 'color'
print(dog.get('color')) # None
print(dog.get('color', '白色')) # 白色(如果不存在的话,返回默认值)
3)实际生活中的字典
定义一个变量保存一个班级的信息:班级名、位置、讲师、班主任、所有学生
class1 = {
'class_name': 'Python2204',
'address': '15教',
'lecturer': {'name': '余婷', 'age': 18, 'qq': '726550822', 'gender': '女'},
'class_teacher': {'name': '静静', 'tel': '110'},
'students': [
{'name': 'stu1', 'age': 21, 'major': '会计', 'tel': '120', 'contacts': {'name': '张三', 'tel': '162723'}},
{'name': 'stu2', 'age': 30, 'major': '电子', 'tel': '219223', 'contacts': {'name': '小明', 'tel': '281912'}},
{'name': 'stu3', 'age': 19, 'major': '旅游管理', 'tel': '123233', 'contacts': {'name': '小花', 'tel': '886552'}},
{'name': 'stu4', 'age': 25, 'major': '通信', 'tel': '4444221', 'contacts': {'name': '李四', 'tel': '22342345'}},
{'name': 'stu5', 'age': 25, 'major': '机械', 'tel': '223111', 'contacts': {'name': '王五', 'tel': '555632'}},
{'name': 'stu6', 'age': 23, 'major': '数学', 'tel': '234234', 'contacts': {'name': '赵六', 'tel': '96533'}}
]
}
# 1)打印班级的名字和教室
print(class1['class_name'], class1['address']) #Python2204 15教
# 2) 打印班级讲师的名字和年龄
lecturer = class1['lecturer']
print(lecturer['name'], lecturer['age']) #余婷 18
# print(class1['lecturer']['name']) # {'name': '余婷', 'age': 18, 'qq': '726550822', 'gender': '女'}['name']
# 3) 打印班主任的电话
print(class1['class_teacher']['tel']) #110
# 4) 打印所有的学生的名字
# 方法一:
all_student = class1['students']
for stu in all_student:
print(stu['name'])
# 方法二:
# ['stu1', 'stu2', ..., 'stu6']
result = [x['name'] for x in class1['students']]
print(result) #['stu1', 'stu2', 'stu3', 'stu4', 'stu5', 'stu6']
# 5)计算所有学生的平均年龄
# 方法一:
all_student = class1['students']
total_age = stu_count = 0
for stu in all_student:
total_age += stu['age']
stu_count += 1
print('平均年龄:', total_age / stu_count) #平均年龄: 23.833333333333332
# 方法二
print('平均年龄:', sum([x['age'] for x in class1['students']]) / len(class1['students']))
# 6) 打印所有学生的联系人的名字
# 方法1:
all_student = class1['students']
for x in all_student:
print(x['contacts']['name'])
# 方法2:
result = [x['contacts']['name'] for x in class1['students']]
print(result)
# 7)打印所有联系人电话号码尾号是2的学生的名字
# ['stu2', 'stu3', 'stu5']
# 方法1:
result = [x['name'] for x in class1['students'] if x['contacts']['tel'][-1] == '2']
print(result)
# 方法2:
for stu in class1['students']:
if stu['contacts']['tel'][-1] == '2':
print(stu['name'])
2.遍历字典
方法1:
for 键 in 字典:
循环体(变量获取的到是键)
方法2:
for 键,值 in 字典.items():
循环体
dog = {'name': '旺财', 'age': 3, 'breed': '土狗', 'gender': '母狗'}
for x in dog:
print('x:', x, dog[x])
for key, value in dog.items():
print(key, value)
3.2.2 字典的增删改
- 改 - 修改某个键对应的值
字典[键] = 新值 - 将字典中指定键对应的值修改成指定的新值
dog = {'name': '旺财', 'age': 3, 'breed': '土狗', 'gender': '母狗'}
print(dog) # {'name': '旺财', 'age': 3, 'breed': '土狗', 'gender': '母狗'}
dog['name'] = '财财'
print(dog) # {'name': '财财', 'age': 3, 'breed': '土狗', 'gender': '母狗'}
- 增 - 添加键值对
1)字典[键] = 值 - 如果键不存在,就在字典中添加键值对; 如果键存在会修改键值对的值
2)字典.setdefault(键, 值) - 在字典中添加指定的键值对;如果键存在会保留原来的值(不会修改)
dog = {'name': '旺财', 'age': 3, 'breed': '土狗', 'gender': '母狗'}
print(dog) # {'name': '旺财', 'age': 3, 'breed': '土狗', 'gender': '母狗'}
dog['color'] = '黄色'
print(dog) # {'name': '旺财', 'age': 3, 'breed': '土狗', 'gender': '母狗', 'color': '黄色'}
dog.setdefault('weight', 15)
print(dog) # {'name': '旺财', 'age': 3, 'breed': '土狗', 'gender': '母狗', 'color': '黄色', 'weight': 15}
# 键存在会修改键值对的值
dog['age'] = 10
print(dog) # {'name': '旺财', 'age': 10, 'breed': '土狗', 'gender': '母狗', 'color': '黄色', 'weight': 15}
# 键存在会保留原来的值(不会修改)
dog.setdefault('gender', '公狗')
print(dog)
goods_list = [
{'name': '泡面', 'price': 4, 'discount': 0.9},
{'name': '火腿肠', 'price': 1.5},
{'name': '矿泉水', 'price': 2, 'discount': 0.8},
{'name': '面包', 'price': 5.5},
{'name': '酸奶', 'price': 7.5}
]
# 给没有折扣商品添加折扣值为1
for goods in goods_list:
goods.setdefault('discount', 1)
print(goods_list)
- 删 - 删除键值对
1)del 字典[键] - 删除字典中指定键对应的键值对
2)字典.pop(键) - 取出字典中指定键对应的值
dog = {'name': '旺财', 'age': 10, 'breed': '土狗', 'gender': '母狗', 'color': '黄色', 'weight': 15}
print(dog) # {'name': '旺财', 'age': 10, 'breed': '土狗', 'gender': '母狗', 'color': '黄色', 'weight': 15}
del dog['gender']
print(dog) # {'name': '旺财', 'age': 10, 'breed': '土狗', 'color': '黄色', 'weight': 15}
color = dog.pop('color')
print(dog, color) # {'name': '旺财', 'age': 10, 'breed': '土狗', 'weight': 15}
3.2.3 相关操作
字典不支持+、*、>、<、>=、<=
- in 和 not in - 判断字典中是否存在或者不存在指定的键
键 in 字典
键 not in 字典
dict1 = {'a': 10, 'b': 20, 'c': 30}
print(10 in dict1) # False
print('b' in dict1) # True
2.相关函数: len、dict
1)len(字典) - 获取字典中键值对的数量
2)dict(数据) - 将指定的数据转换成字典
能转换成字典的数据的要求:
a.数据本身是一个序列
b.序列中的元素必须是且只有两个元素的小序列
c.小序列的第一个元素必须是不可变类型的数据
result = dict(['ab', 'cd', 'ef'])
print(result) # {'a': 'b', 'c': 'd', 'e': 'f'}
result = dict([('name', 'xiaoming'), ('age', 18)])
print(result) # {'name': 'xiaoming', 'age': 18}
注意:字典转换成列表的时候,将字典所有的键作为列表的元素
dog = {'name': '旺财', 'age': 10, 'breed': '土狗', 'gender': '母狗', 'color': '黄色', 'weight': 15}
print(list(dog)) # ['name', 'age', 'breed', 'gender', 'color', 'weight']
3.相关方法:字典.xxx()
1)字典.clear() - 清空字典
2)字典.copy() - 复制字典产生一个一模一样的新字典
3)字典.keys() - 获取字典所有的键,返回一个序列
字典.values() - 获取字典所有的值,返回一个序列
字典.items() - 将字典转换成一个序列,并且将每一个键值对转换成一个元组
dog = {'name': '旺财', 'age': 10, 'breed': '土狗', 'gender': '母狗', 'color': '黄色', 'weight': 15}
print(dog.keys()) #dict_keys(['name', 'age', 'breed', 'gender', 'color', 'weight'])
print(dog.values()) #dict_values(['旺财', 10, '土狗', '母狗', '黄色', 15])
print(dog.items()) #dict_items([('name', '旺财'), ('age', 10), ('breed', '土狗'), ('gender', '母狗'), ('color', '黄色'), ('weight', 15)])
4)字典1.update(字典2) - 将字典2中所有的键值对都添加到字典1
d1 = {'a': 10, 'b': 20}
d2 = {'x': 100, 'y': 200}
d1.update(d2)
print(d1) # {'a': 10, 'b': 20, 'x': 100, 'y': 200}
今日作业
-
定义一个变量保存一个学生的信息,学生信心中包括:姓名、年龄、成绩(单科)、电话、性别
stu1 = {'name':'张三','age':21,'score':90,'tel':110,'gender':'male'} print(stu1)
-
定义一个列表,在列表中保存6个学生的信息(学生信息中包括: 姓名、年龄、成绩(单科)、电话、性别(男、女、不明) )
list1 = [{'name':'stu1','age':20,'score':100,'tel':1105678,'gender':'male'},
{'name':'stu2','age':19,'score':59,'tel':115671,'gender':'female'},
{'name':'stu3','age':21,'score':80,'tel':11234,'gender':'male'},
{'name':'stu4','age':18,'score':88,'tel':1135678,'gender':'不明'},
{'name':'stu5','age':19,'score':55,'tel':1142345,'gender':'不明'},
{'name':'stu6','age':20,'score':85,'tel':11542,'gender':'female'}]
(1)统计不及格学生的个数
count = 0
for i in list1:
if i['score'] < 60:
count += 1
print(count)
(2)打印不及格未成年学生的名字和对应的成绩
# 方法一:
for i in list1:
if i['score'] < 60 and i['age'] < 18:
print(i['name'],i['score'])
# 方法二:
list2=[(i['name'],i['score']) for i in list1 if i['score'] < 60 and i['age'] < 18]
print(list2) #[('stu5', 55)]
(3)求所有男生的平均年龄
count = 0
sum = 0
for i in list1:
if i['gender'] == 'male':
count +=1
sum += i['age']
print(sum/count)
(4)打印手机尾号是8的学生的名字
name1=[i['name'] for i in list1 if i['tel'] % 10 == 8]
print(name1)
(5)打印最高分和对应的学生的名字
list3=[]
for i in list1:
list3.append(i['score'])
list3.sort()
if i['score'] == list3[-1]:
print(i['score'],i['name'])
(6)删除性别不明的所有学生
list4=[list1[i] for i in range(len(list1)) if list1[i]['gender'] != '不明']
print(list4)
(7)将列表按学生成绩从大到小排序(挣扎一下,不行就放弃)
for i in range(1,len(list4)):
for j in range(0,len(list4)-i):
if list4[j]['score'] > list4[j+1]['score']:
list4[j]['score'],list4[j+1]['score']=list4[j+1]['score'],list4[j]['score']
print(list4)
-
定义一个变量保存一个班级的信息,班级信息中包括:班级名称、教室位置、班主任信息、讲师信息、班级所有的学生(根据实际情况确定数据类型和具体信息)
class1={ 'class_name':'python2204', 'class_location':'15classroom', 'class_teacher':{'name':'静姐','gender':'female','position':'未知','tel':234567890,'QQ':234523,'WX':1563214}, 'lecturer':[{'name': '婷姐','gender':'female','position':'lecturer','tel':15632452,'QQ':563255,'WX':56321563}, {'name': '付哥','gender':'male','position':'lecturer','tel':14523422,'QQ':63252452,'WX':523563}], 'students': [ {'name': 'stu1', 'age': 21,'gender':'male', 'major': '会计', 'tel': '120', 'contacts': {'name': '张三', 'tel': '162723'}}, {'name': 'stu2', 'age': 26,'gender':'female', 'major': '电子', 'tel': '219223', 'contacts': {'name': '小明', 'tel': '281912'}}, {'name': 'stu3', 'age': 19,'gender':'male', 'major': '旅游管理', 'tel': '123233', 'contacts': {'name': '小花', 'tel': '886552'}}, {'name': 'stu4', 'age': 22,'gender':'female', 'major': '通信', 'tel': '4444221', 'contacts': {'name': '李四', 'tel': '22342345'}}, {'name': 'stu5', 'age': 21,'gender':'male', 'major': '机械', 'tel': '223111', 'contacts': {'name': '王五', 'tel': '555632'}}, {'name': 'stu6', 'age': 230,'gender':'female', 'major': '数学', 'tel': '234234', 'contacts': {'name': '赵六', 'tel': '96533'}} ] }
-
已知一个列表保存了多个狗对应的字典:
dogs = [ {'name': '贝贝', 'color': '白色', 'breed': '银狐', 'age': 3, 'gender': '母'}, {'name': '花花', 'color': '灰色', 'breed': '法斗', 'age': 2}, {'name': '财财', 'color': '黑色', 'breed': '土狗', 'age': 5, 'gender': '公'}, {'name': '包子', 'color': '黄色', 'breed': '哈士奇', 'age': 1}, {'name': '可乐', 'color': '白色', 'breed': '银狐', 'age': 2}, {'name': '旺财', 'color': '黄色', 'breed': '土狗', 'age': 2, 'gender': '母'} ]
(1)利用列表推导式获取所有狗的品种
[‘银狐’, ‘法斗’, ‘土狗’, ‘哈士奇’, ‘银狐’, ‘土狗’]
dog_breed = [i['breed'] for i in dogs] print(dog_breed)
(2)利用列表推导式获取所有白色狗的名字
[‘贝贝’, ‘可乐’]
white_dog_name = [i['name'] for i in dogs if i['color'] == '白色'] print(white_dog_name)
(3)给dogs中没有性别的狗添加性别为 ‘公’
for i in dogs: i.setdefault('gender','公') print(dogs)
(4)统计 ‘银狐’ 的数量
count = 0 for i in dogs: if i['breed'] == '银狐': count += 1 print(count)