day8-字典
一.认识字典
-
字典和列表的选择:
需要同时保存多个数据的时候,如果多个数据的意义相同(不需要区分)就使用列表;如果多个数据的意义不同就使用字典
-
认识字典(dict)
""" 1) 是容器型数据类型; 将{}作为容器的标志,里面多个键值对用逗号隔开: {键1: 值1, 键2: 值2, 键3: 值3,...} 键值对的格式: 键:值 2) 特点 字典是可变的(支持增删改); 字典是无序(不支持下标,元素顺序不影响结果) 3) 对元素的要求 字典的元素是键值对 a. 键的要求: 键必须是不可变的类型的数据(数字、字符串、布尔、元组等);键是唯一的 b. 值的要求: 没有要求 """ # 空字典 dict1 = {} # 字典中的元素只能是键值对 dict2 = {'name': '小明', 'age': 20} print(dict2) # dict3 = {'name': '张三', 30} # 报错! 30不是键值对 # 字典无序 print({'a': 10, 'b': 20} == {'b': 20, 'a': 10}) # True # 键是不可变类型的数据 dict3 = {10: 23, 1.23: 10, 'abc': 30, (1, 2): 50} print(dict3) # dict4 = {10: 23, 1.23: 10, 'abc': 30, [1, 2]: 50} # 报错! # 键是唯一 dict4 = {'a': 10, 'b': 20, 'c': 30, 'a': 100} print(dict4) # {'a': 100, 'b': 20, 'c': 30}
二.字典的基本操作
-
查 - 获取字典的值
查单个(重要) - 一次获取一个值
""" 语法1:字典[键] - 获取字典中指定键对应的值; 如果键不存在会报错! 语法2: 字典.get(键) - 获取字典中指定键对应的值; 如果键不存在不会报错,并且返回None 字典.get(键, 默认值) - 获取字典中指定键对应的值; 如果键不存在不会报错,并且返回默认值 """ dog = {'name': '旺财', 'age': 3, 'breed': '中华田园犬', 'color': '白色'} print(dog['age']) print(dog['name']) # print(dog['weight']) # 报错! KeyError: 'weight' print(dog.get('breed')) print(dog.get('color')) print(dog.get('weight')) # None print(dog.get('weight', 5)) # 5
-
列表和字典正确的打开方式
# 定义一个变量保存一个班级的信息 class1 = { 'name': 'python2201', 'address': '12教室', 'lecturer': { 'name': '余婷', 'gender': '女', 'tel': '13678192302' }, 'class_teacher': { 'name': '张瑞燕', 'gender': '女', 'tel': '110', 'age': 20, 'QQ': '617818271' }, 'students': [ {'name': '小明', 'gender': '男', 'age': 18, 'score': 100, 'education': '专科', 'linkman': {'name': '小吴', 'tel': '110'}}, {'name': '小花', 'gender': '女', 'age': 20, 'score': 98, 'education': '本科', 'linkman': {'name': '小张', 'tel': '120'}}, {'name': '张三', 'gender': '男', 'age': 30, 'score': 90, 'education': '本科', 'linkman': {'name': '小赵', 'tel': '119'}}, {'name': '李四', 'gender': '男', 'age': 22, 'score': 70, 'education': '专科', 'linkman': {'name': '小刘', 'tel': '134'}}, {'name': '王二', 'gender': '男', 'age': 28, 'score': 100, 'education': '本科', 'linkman': {'name': '小徐', 'tel': '2383'}}, {'name': '赵敏', 'gender': '女', 'age': 27, 'score': 99, 'education': '专科', 'linkman': {'name': '小胡', 'tel': '23423'}}, {'name': '老王', 'gender': '男', 'age': 22, 'score': 89, 'education': '本科', 'linkman': {'name': '小王', 'tel': '1234'}} ] } # 1) 获取班级名字 print(class1['name']) # 2) 获取讲师的名字 # teacher = class1['lecturer'] # print(teacher['name']) print(class1['lecturer']['name']) # 3) 获取班主任电话号码 print(class1['class_teacher']['tel']) # 4) 统计学生中男生的数量 all_student = class1['students'] count = 0 for stu in all_student: if stu['gender'] == '男': count += 1 print('男生的数量:', count) # 5) 计算所有学生分数的平均分 # 方法一: # total_score = 0 # for stu in all_student: # total_score += stu['score'] # print('平均分:', total_score / len(all_student)) # 方法二: result = sum([stu['score'] for stu in all_student]) / len(all_student) print('平均分:', result) # 6) 获取分数最高的学生的名字 # 方法一:先获取最高分,然后再看谁的分数和最高分相等 max_score = max(stu['score'] for stu in all_student) names = [stu['name'] for stu in all_student if stu['score'] == max_score] print(names) # 方法二: # 假设第一个学生的分数最高 max_score = all_student[0]['score'] names = [all_student[0]['name']] for stu in all_student[1:]: score = stu['score'] if score > max_score: max_score = score names.clear() names.append(stu['name']) elif score == max_score: names.append(stu['name']) print(max_score, names) # 7) 获取所有紧急联系人的电话 for stu in all_student: print(stu['linkman']['tel'])
-
遍历
""" 1) for 键 in 字典: pass 2) for 键,值 in 字典.items(): pass """ stu = {'name': '小明', 'gender': '男', 'age': 18, 'score': 100, 'education': '专科'} for x in stu: print(x, stu[x]) print('------------------------') for key, value in stu.items(): print(key, value) print(stu.items()) for x in stu.items(): print(x)
三.字典增删改
-
增/改 - 添加键值对
""" 1) 字典[键] = 值 如果键存在就修改指定键对应的值;如果键不存在就添加键值对 2) 字典.setdefault(键, 值) 添加键值对(如果键不存在就添加键值对,如果键存在不动字典) """
例:
cat = {'name': '花花', 'breed': '加菲', 'color': '白色'} print(cat) # 修改 cat['name'] = '小白' print(cat) # {'name': '小白', 'breed': '加菲', 'color': '白色'} # 添加 cat['age'] = 2 print(cat) # {'name': '小白', 'breed': '加菲', 'color': '白色', 'age': 2} # 添加2 cat.setdefault('price', 1000) print(cat) # {'name': '小白', 'breed': '加菲', 'color': '白色', 'age': 2, 'price': 1000}
练习:给没有折扣的商品添加折扣值为1
all_goods = [ {'name': '泡面', 'price': 3.5, 'count': 1723, 'discount': 0.5}, {'name': '矿泉水', 'price': 2, 'count': 91723}, {'name': '面包', 'price': 5, 'count': 290}, {'name': '火腿肠', 'price': 1, 'count': 923, 'discount': 0.95} ] for x in all_goods: x.setdefault('discount', 1) print(all_goods)
-
删 - 删除键值对
""" del 字典[键] - 删除指定键对应的键值对 字典.pop(键) - 取出指定键对应的值 """ cat = {'name': '小白', 'breed': '加菲', 'color': '白色', 'age': 2, 'price': 1000} del cat['breed'] print(cat) # {'name': '小白', 'color': '白色', 'age': 2, 'price': 1000} result = cat.pop('color') print(cat, result) # {'name': '小白', 'age': 2, 'price': 1000} 白色
四.字典相关操作函数和方法
-
相关操作
-
运算符:字典不支持 +、*、>、<、>=、<=,只支持 == 、!=
-
in 和 not in - 字典的in和not in操作判断的是字典中是否存在指定的键
# 键 in 字典 dict1 = {'a': 10, 'b': 20, 'c': 30} print(10 in dict1) # False print('a' in dict1) # True
-
-
相关函数:len、dict
""" a. len(字典) - 获取字典中键值对的个数 b. dict(数据) - 将指定数据转换成字典 对数据的要求:1. 数据本身是一个序列 2. 序列中的元素必须都是有且只有两个元素的小序列,并且其中第一个元素是不可变的数据 """ print(len(dict1)) seq = ['ab', 'cd', 'ef'] print(dict(seq)) # {'a': 'b', 'c': 'd', 'e': 'f'} seq = [(10, 20), range(2), 'he'] print(dict(seq)) # {10: 20, 0: 1, 'h': 'e'}
-
相关方法
-
字典.clear()
-
字典.copy()
-
字典.keys()
-
字典.values()
-
字典.items()
dog = {'name': '大黄', 'breed': '土狗', 'gender': '母狗'} print(dog.keys()) # dict_keys(['name', 'breed', 'gender']) print(dog.values()) # dict_values(['财财', '土狗', '母狗']) print(dog.items()) # dict_items([('name', '财财'), ('breed', '土狗'), ('gender', '母狗')])
-
update
-
字典.update(序列) - 将可以序列中的元素全部添加字典中(序列必须是可以转换成字典的序列)
-
字典1.update(字典2) - 将字典2中所有的键值对都添加到字典1中
dict1 = {'a': 10, 'b': 20} dict2 = {'c': 100, 'd': 200, 'a': 1000} dict1.update(dict2) print(dict1)
-
-
五.字典推导式
"""
{表达式1:表达式2 for 变量 in 序列}
{表达式1:表达式2 for 变量 in 序列 if 条件语句}
"""
result = {x: x*2 for x in range(5)}
print(result)
result = {x: x for x in range(10) if x % 3}
print(result)
作业
-
定义一个变量保存一个学生的信息,学生信息中包括:姓名、年龄、成绩(单科)、电话、性别
student = { 'name':'陈志东' , 'age': 23, 'score': 100, 'tel': '18782667516', 'gender':'男' } print(student)
-
定义一个列表,在列表中保存6个学生的信息(学生信息中包括: 姓名、年龄、成绩(单科)、电话、性别(男、女、不明) )
-
统计不及格学生的个数
-
打印不及格未成年学生的名字和对应的成绩
-
求所有男生的平均年龄
-
打印手机尾号是8的学生的名字
-
打印最高分和对应的学生的名字
-
删除性别不明的所有学生
-
将列表按学生成绩从大到小排序(挣扎一下,不行就放弃)
students = [ {'name':'陈志东' ,'age': 23,'score': 90,'tel': '187826','gender':'男'}, {'name':'孙香' ,'age': 22,'score': 100,'tel': '17378','gender':'女'}, {'name':'秦香怡' ,'age': 24,'score': 80,'tel': '13408','gender':'女'}, {'name':'秦佳怡' ,'age': 16,'score': 50,'tel': '110','gender':'女'}, {'name':'秦文怡' ,'age': 29,'score': 78,'tel': '120','gender':'女'}, {'name':'何海龙' ,'age': 28,'score': 56,'tel': '119','gender':'不明'} ] # 1 count = 0 for i in students: if i['score'] < 60: count += 1 print(count) # 2 for i in students: if i['score'] < 60 and i['age'] < 18: print(i['name'],i['score']) # 3 result = [i['age'] for i in students if i['gender'] == '男'] print(sum(result) / len(result)) # 4 result = [i['name'] for i in students if i['tel'][-1] == '8'] print(result) # 5 max_score = students[0]['score'] names = [students[0]['name']] for i in students: score = i['score'] if score > max_score: max_score = score names.clear() names.append(i['name']) elif score == max_score: names.append(i['name']) print(max_score,names) # 6 for i in range(len(students)): if students[i]['gender'] == '不明': del students[i] print(students) # 7 score = [x['score'] for x in students] new_list = sorted(score,reverse=True) scores = [] for i in students: for j in range(len(new_list)): if new_list[j] == i['score']: scores.insert(j,i) print(scores)
-
-
定义一个变量保存一个班级的信息,班级信息中包括:班级名称、教室位置、班主任信息、讲师信息、班级所有的学生(根据实际情况确定数据类型和具体信息)
class1 = { 'name':'python2201', 'adress':'12教室', 'class_teacher':{ 'name':'张瑞燕', 'gender':'女', 'age':'18', 'tel':'1623456' }, 'lecturer':{ 'name':'余婷', 'gender':'女', 'age':'18', 'tel':'1623456' }, 'students':[ {'name': '陈志东', 'age': 23, 'score': 90, 'tel': '18782667516', 'gender': '男'}, {'name': '田伟', 'age': 22, 'score': 100, 'tel': '17378589778', 'gender': '男'}, {'name': '王雨轩', 'age': 24, 'score': 80, 'tel': '13408261924', 'gender': '男'}, {'name': '陈翔', 'age': 16, 'score': 50, 'tel': '11023155622', 'gender': '男'}, {'name': '何周洋', 'age': 25, 'score': 78, 'tel': '12136568128', 'gender': '男'}, {'name': '代欣锐', 'age': 22, 'score': 100, 'tel': '11921343545', 'gender': '女'} ] } print(class1)
-
已知一个列表保存了多个狗对应的字典:
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': '母'} ]
-
利用列表推导式获取所有狗的品种
result = [i['breed'] for i in dogs] print(result)
-
利用列表推导式获取所有白色狗的名字
result = [i['name'] for i in dogs if i['color'] == '白色'] print(result
-
给dogs中没有性别的狗添加性别为 ‘公’
for i in dogs: i.setdefault('gender','公') print(dogs)
-
统计 ‘银狐’ 的数量
count = 0 for i in dogs: if i['breed'] == '银狐': count += 1 print(count)
-