字典
1.认识字典
1.字典和列表的选择:
需要同时保存多个数据的时候,如果多个数据的意义相同(不需要区分)就使用列表;
如果多个数据的意义不同就使用字典
2.认识字典(dict)
-
- 是容器型数据类型;
- 将{}作为容器的标志,里面多个键值对用逗号隔开:{键1: 值1, 键2: 值2, …}
- 键值对的格式: 键:值
- 特点
- 字典是可变的(支持增删改)
- 字典是无序(不支持下标,元素顺序不影响结果)
- 对元素的要求
- 字典的元素是键值对
- 键的要求: 键必须是不可变的类型的数据(数字、字符串、布尔、元组等);键是唯一的
- 值的要求: 没有要求
# 空字典
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}
2.字典基本操作
1.查 - 获取字典的值
-
查单个(重要) - 一次获取一个值
-
语法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
-
-
遍历
- for 键 in 字典:
pass - for 键,值 in 字典.items():
pass
- for 键 in 字典:
2.列表和字典正确的打开方式
# 定义一个变量保存一个班级的信息
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'])
3.字典增删改
1.增/改 - 添加键值对
-
字典[键] = 值
如果键存在就修改指定键对应的值;如果键不存在就添加键值对
-
字典.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)
2.删 - 删除键值对 (了解)
-
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} 白色
4.字典相关操作函数和方法
1.相关操作
- 运算符:字典不支持 +、*、>、<、>=、<=,只支持 == 、!=
- in 和 not in - 字典的in和not in操作判断的是字典中是否存在指定的键
# 键 in 字典
dict1 = {'a': 10, 'b': 20, 'c': 30}
print(10 in dict1) # False
print('a' in dict1) # True
2.相关函数:len、dict
-
len(字典) - 获取字典中键值对的个数
-
dict(数据) - 将指定数据转换成字典
- 要求数据本身是一个序列
- 要求序列中的元素必须都是有且只有两个元素的小序列,并且其中第一个元素是不可变的数据
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'}
3.相关方法
- 字典.clear()
- 字典.copy()
-
- 字典.keys() - 返回一个序列,序列中的元素是字典所有的键
- 字典.values() - 返回一个序列,序列中的元素是字典所有的值
- 字典.items() - 返回一个序列,序列中的元素是由每一对键和值组成的元组
- update
- 字典.update(序列) - 将可以序列中的元素全部添加字典中(序列必须是可以转换成字典的序列)
- 字典1.update(字典2) - 将字典2中所有的键值对都添加到字典1中
5.字典推导式(了解)
- {表达式1:表达式2 for 变量 in 序列}
- {表达式1:表达式2 for 变量 in 序列 if 条件语句}
作业
-
定义一个变量保存一个学生的信息,学生信心中包括:姓名、年龄、成绩(单科)、电话、性别
stu = { 'name': '张三', 'age': 20, 'score': 94, 'tel': '13888676788', 'gender': '男' } print(stu)
-
定义一个列表,在列表中保存6个学生的信息(学生信息中包括: 姓名、年龄、成绩(单科)、电话、性别(男、女、不明) )
- 统计不及格学生的个数
- 打印不及格未成年学生的名字和对应的成绩
- 求所有男生的平均年龄
- 打印手机尾号是8的学生的名字
- 打印最高分和对应的学生的名字
- 删除性别不明的所有学生
- 将列表按学生成绩从大到小排序(挣扎一下,不行就放弃)
stu = [ {'name': '张三', 'age': 18, 'score': 48, 'tel': '15656787856', 'gender': '男'}, {'name': '小红', 'age': 20, 'score': 98, 'tel': '18778906788', 'gender': '女'}, {'name': '李四', 'age': 16, 'score': 56, 'tel': '13678904561', 'gender': '不明'}, {'name': '王芳', 'age': 22, 'score': 95, 'tel': '12345678909', 'gender': '女'}, {'name': '小明', 'age': 24, 'score': 74, 'tel': '18892341908', 'gender': '不明'}, {'name': '李玉', 'age': 23, 'score': 64, 'tel': '13135356767', 'gender': '男'} ] # 1.统计不及格学生的个数 count = 0 for x in stu: if x['score'] < 60: count += 1 print(count) # 2.打印不及格未成年学生的名字和对应的成绩 for x in stu: if x['score'] < 60 and x['age'] < 18: print(x['name'],x['score']) # 3.求所有男生的平均年龄 num = 0 new_age = [] for x in stu: if x['gender'] == '男': num += x['age'] new_age.append(x['age']) print(num/len(new_age)) # 4.打印手机尾号是8的学生的名字 for x in stu: y = list(x['tel']) if int(y[-1]) == 8: print(x['name']) # 5.打印最高分和对应的学生的名字 max1 = stu[0]['score'] names = [stu[0]['name']] for x in stu[1:]: if max1 < x['score']: max1 = x['score'] names.clear() names.append(x['name']) elif x['score'] == max1: names.append(x['name']) print(max1,names) # 6.删除性别不明的所有学生 new_stu = [] for x in stu: if x['gender'] != '不明': new_stu.append(x) print(new_stu) # 7.将列表按学生成绩从大到小排序(挣扎一下,不行就放弃) result = sorted(students, key=lambda x: x['score'], reverse=True) print(result) result = max(students, key=lambda x: x['age']) print(result)
-
定义一个变量保存一个班级的信息,班级信息中包括:班级名称、教室位置、班主任信息、讲师信息、班级所有的学生(根据实际情况确定数据类型和具体信息)
class1 = { 'name': 'Python2201班', 'place': '12号教室', 'lead_teacher': { 'name': '张瑞燕', 'gender': '女', 'age': 30, 'QQ': 1626889221, 'tel': 15678903456 }, 'lecturer': { 'name': '余婷', 'genger': '女', 'tel': '17890907878' }, 'student': [ {'name': '小明', 'gender': '男', 'age': 18, 'score': 100, 'education': '专科'}, {'name': '小花', 'gender': '女', 'age': 20, 'score': 98, 'education': '本科'}, {'name': '张三', 'gender': '男', 'age': 30, 'score': 90, 'education': '本科'}, {'name': '李四', 'gender': '男', 'age': 22, 'score': 70, 'education': '专科'}, {'name': '王二', 'gender': '男', 'age': 28, 'score': 100, 'education': '本科'}, {'name': '赵敏', 'gender': '女', 'age': 27, 'score': 99, 'education': '专科'}, {'name': '老王', 'gender': '男', 'age': 22, 'score': 89, 'education': '本科'} ] }
-
已知一个列表保存了多个狗对应的字典:
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 = [x['breed'] for x in dogs] print(result)
-
利用列表推导式获取所有白色狗的名字
[‘贝贝’, ‘可乐’]
result = [x['name'] for x in dogs if x['color'] == '白色'] print(result)
-
给dogs中没有性别的狗添加性别为 ‘公’
for x in dogs: x.setdefault('gender', '公') print(dogs)
-
统计 ‘银狐’ 的数量
count = 0 for x in dogs: if x['breed'] == '银狐': count += 1 print(count)
-