day8 - 字典
字典和列表
字典和列表的选择:需要同时保存多个数的时候,如果多个数据的意义(不需要区分)就使用列表;如果多个数锯的意义不同就是用字典
认识字典(dict)
1)是容器型数据类型;
将{}作为容器的标志,里面多个键值对用逗号隔开:{键1:值1,键2:值2,键3:值3…}
键值对的格式: 键:值
2) 字典是可变的(支持增删改);字典是无序(不支持下标,元素顺序不影响结果)
3) 对元素的要求
字典的元素是键值对
a. 键的要求:键必须是不可变类型的数据(数字、字符串、布尔、元组等);键是唯一的
b. 值得要求:没有要求
# 空字典
dict1 = {}
# 字典中的元素只能是键值对
dict2 = {'name':'小明','age':20}
# 字典无序
print({'a':10,'b':20} == {'b': 20, 'a':10})
# 键是不可变类型数据
dict3 = {10:23,1.23:10,'abc':30,(1,2):50}
print(dict3)
# 键是唯一的
dict4 = {'a':10,'b':20,'c':30,'a':100}
print(dict4) # 打印结果保留后面那个
字典的基本操作
1) 查单个(重要) - 一次获取一个值
语法1:字典[键] - 获取字典中指定键对的值;如果间不存在会报错!
语法2: 字典.get(键) - 获取字典中指定键对的值;如果键不存在不会报错,并且返回None
字典.get(键,默认值)
练习
dog = {'name':'旺财','age':3,'breed':'土狗','color':'白色'}
print(dog['age'])
print(dog['name'])
# print(dog['weight']) # 报错
print(dog.get('color'))
print(dog.get('weight')) # 不错报错,返回空值
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.get('name'))
# 2) 获取讲师的名字
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) 计算所有学生分数的平均分
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]
# 方法二:
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'])
遍历
-
直接遍历
for 键 in 字典:
pass
for 键,值 in 字典.items():
pass
stu = {'name': '小明', 'gender': '男', 'age': 18, 'score': 100, 'education': '专科', 'linkman': {'name': '小吴', 'tel': '110'}}
for x in stu:
print(x,stu[x])
print('---------------------------------------------')
for key,value in stu.items():
print(key,value)
print(stu.items())
字典的增删改
增/改 - 添加键值对
1)字典[键] = 值 如果键存在就修改指定对应的值;如果不存在就添加键值对
2)字典.setdefault(键,值) 添加键值对(如果键不存在就添加键值对;如果存在就不动)
cat = {'name':'花花','breed':'加菲','color':'白色'}
print(cat)
# 修改
cat['name'] = '小白'
print(cat)
# 添加
cat['age'] = '2'
print(cat)
# 添加2
cat.setdefault('price','200')
print(cat)
删 - 删除键值对
del 字典[键] - 删除指定键对应的键值对
字典.pop(键) - 取出键值对的值
cat = {'name': '小白', 'breed': '加菲', 'color': '白色', 'age': '2', 'price': '200'}
del cat['breed']
print(cat)
result = cat.pop('color')
print(cat,result)
字典的相关操作函数和方法
相关操作
1) 字典不支持:+、*、<、>、>=、<=,只支持:==、!=
2) in 和 not in - 字典的in和 not in操作判断的是字典中是否存在指定的键
键 in 字典
相关函数:len、dict
a. len(字典) - 获取字典中键值对的个数
b. dict(数据) - 将指定数据转换成字典
对数据的要求:1. 数据本身是一个序列
2. 序列中的元素都必须是有且只有两个元素的小序列,并且其中第一个元素是不可变的数据
seq = ['ab','cd','ef']
print(dict(seq))
seq = [(10,20),range(2),'he']
print(dict(seq))
相关方法
字典.get()
字典.setdefault()
a. 字典.clear()
b. 字典.copy()
c.
字典.kes() - 返回一个序列;序列中的元素是字典的所有的键
字典.value() - 返回一个序列;序列中的元素是字典的所有的值
字典.items() - 返回一个序列;序列中的元素是由键和值组成的元组
d. update
字典.update(序列) - 将序列中的元素全部添加到字典中(序列必须是可以转换橙子点的序列)
字典1.update(字典2) - 将字典中2中所有的键对值添加到字典1中
作业
-
定义一个变量保存一个学生的信息,学生信心中包括:姓名、年龄、成绩(单科)、电话、性别
a = {'name':'joker','age':'18','score':'60','tel':'110','gender': '男'}
-
定义一个列表,在列表中保存6个学生的信息(学生信息中包括: 姓名、年龄、成绩(单科)、电话、性别(男、女、不明) )
-
统计不及格学生的个数
count = 0 for stu in b: if int(stu['score']) < 60: count += 1 print(count)
-
打印不及格未成年学生的名字和对应的成绩
c = {stu['name']:stu['score'] for stu in b if int(stu['score'])<60} print(c)
-
求所有男生的平均年龄
d = sum([int(stu['age']) for stu in b ])/len(b) print(d)
-
打印手机尾号是8的学生的名字
e = [stu['name'] for stu in b if int(stu['tel'])%10==8] print(e)
-
打印最高分和对应的学生的名字
-
gf = b[0]['score'] gfr = [b[0]['name']] for stu in b[1:]: fs = stu['score'] if gf < fs: gf = fs gfr.clear() gfr.append(stu['name']) print(gfr) 方法二 maxf = max(stu['score']for stu in b) gfr1= [stu['name']for stu in b if stu['score']==maxf] print(gfr1)
-
删除性别不明的所有学生
-
f = b.copy() for stu in b: if stu['gender']=='不明': f.remove(stu) print(f)
-
将列表按学生成绩从大到小排序(挣扎一下,不行就放弃)
-
gf = [x['score'] for x in b ] pm = sorted(gf,reverse=True) h = [] for i in range(len(pm)): for y in b: if y['score'] == pm[i] : h.insert(i,y) print(h)
-
-
定义一个变量保存一个班级的信息,班级信息中包括:班级名称、教