day-字典元组和集合
1.认识字典
stu = [‘小明’, 45, 175, 75, 30, ‘女’]
print(stu[1])
stu = {‘name’: ‘小明’, ‘age’: 45, ‘height’: 175, ‘体重’: 75, ‘score’: 30, ‘gender’: ‘女’}
print(stu[‘age’])
用一个容器同时保存多个数据的时候的建议:如果多个数据的意义相同用列表,如果多个数据的意义不同用字典
- 什么是字典(dict)
“”"
- 字典是容器型数据类型; 将{}作为容器的标志,里面多个元素用逗号隔开,元素必须是键值对:{键1:值1, 键2:值2, 键3:值3,…}
- 字典是可变的(支持增删改); 字典是无序的(不支持下标操作)
- 元素的要求:
a. 键:键必须是不可变的数据类型的数据(一般用字符串); 键是唯一的
b. 值:没有要求
“”"
空字典
dict1 = {}
print(len(dict1), type(dict1)) # 0
字典是无序的
print({‘a’: 10, ‘b’: 20} == {‘b’: 20, ‘a’: 10}) # True
字典的键是不可变的数据
dict2 = {10: 20, 1.2: 30, ‘a’: 10, True: 20, (1, 2): 30}
dict3 = {10: 20, 1.2: 30, ‘a’: 10, True: 20, [1, 2]: 30} # 报错!
键是唯一的
dict4 = {‘a’: 10, ‘b’: 20, ‘c’: 30, ‘a’: 100}
print(dict4) # {‘a’: 100, ‘b’: 20, ‘c’: 30}
2.字典的查操作
1.查单个(重要) - 获取单个值
“”"
语法1:字典[键] - 获取指定键对应的值, 键如果不存在会报错
语法2:字典.get(键) - 获取指定键对应的值, 键如果不存在不会报错而是返回None
语法3:字典.get(键, 默认值) - 获取指定键对应的值, 键如果不存在不会报错而是返回默认值
“”"
dog = {'name': '财财', 'gender': '母狗', 'breed': '哈士奇', 'age': 3}
print(dog['gender']) # 母狗
print(dog['age']) # 3
print(dog.get('name')) # 财财
print(dog.get('breed')) # 哈士奇
# print(dog['price']) # 报错! KeyError: 'price'
print(dog.get('price')) # None
print(dog.get('age', 1)) # 3
print(dog.get('price', 0)) # 0
class1 = {
'name': 'Python2202',
'address': '14教室',
'lecturer': {'name': '余婷', 'qq': '726550822', 'gender': '女', 'age': 18},
'head_teacher': {'name': '舒玲', 'tel': '110', 'gender': '女', 'age': 18},
'students': [
{'name': '罗浩', 'tel': '120', 'gender': '男', 'major': '软件工程', 'age': 20, 'linkman': {'name': 'p1', 'tel': '29372'}},
{'name': 'stu1', 'tel': '62736', 'gender': '女', 'major': '电子信息', 'age': 23, 'linkman': {'name': 'p2', 'tel': '78221'}},
{'name': 'stu2', 'tel': '1292831', 'gender': '女', 'major': '会计', 'age': 27, 'linkman': {'name': 'p3', 'tel': '28239'}},
{'name': 'stu3', 'tel': '72289392', 'gender': '男', 'major': '数学', 'age': 21, 'linkman': {'name': 'p4', 'tel': '29102'}},
{'name': 'stu4', 'tel': '2737288', 'gender': '女', 'major': '计算机', 'age': 32, 'linkman': {'name': 'p5', 'tel': '236721'}},
{'name': 'stu5', 'tel': '27361028', 'gender': '男', 'major': '物理', 'age': 19, 'linkman': {'name': 'p6', 'tel': '34293'}},
{'name': 'stu6', 'tel': '829129', 'gender': '男', 'major': '石油', 'age': 22, 'linkman': {'name': 'p7', 'tel': '229311'}}
]
}
# 1). 获取班级名
print(class1['name'])
# 2). 获取讲师的名字
print(class1['lecturer']['name'])
# 3). 获取班主任的电话
print(class1['head_teacher']['tel'])
# 4). 打印所有学生的名字
# 方法1:
for stu in class1['students']:
print(stu['name'])
# 方法2:
print([stu['name'] for stu in class1['students']])
# 5). 统计学生中男生的个数
count = 0
for stu in class1['students']:
if stu['gender'] == '男':
count += 1
print(count)
# 6). 计算班级学生的平均年龄
total_age = 0
count = 0
for stu in class1['students']:
total_age += stu['age']
count += 1
print(f'平均年龄:{total_age / count:.2f}')
# 7). 打印所有学生的联系人的电话号码
for stu in class1['students']:
print(stu['linkman']['tel'])
2.遍历
for 变量 in 字典:
循环体
注意:变量依次取到的是字典所有的键
dog = {'name': '财财', 'gender': '母狗', 'breed': '哈士奇', 'age': 3}
for x in dog:
print(x, dog[x])
3.字典的增删改
1.增、改
“”"
语法1:字典[键] = 值 - 如果键不存在就添加键值对;如果键存在就修改指定键对应的值
语法2:字典.setdefault(键, 值) - 添加键值对(键不存在会添加,键存在不会修改)
“”"
goods = {‘name’: ‘老坛酸菜泡面’, ‘price’: 3.5, ‘weight’: 300}
print(goods) # {‘name’: ‘老坛酸菜泡面’, ‘price’: 3.5, ‘weight’: 300}
键不存是增加
goods[‘保质期’] = 30
print(goods) # {‘name’: ‘老坛酸菜泡面’, ‘price’: 3.5, ‘weight’: 300, ‘保质期’: 30}
键存在是修改
goods[‘price’] = 3
print(goods) # {‘name’: ‘老坛酸菜泡面’, ‘price’: 3, ‘weight’: 300, ‘保质期’: 30}
print(‘------------------------------------华丽的分割线-----------------------------------’)
goods = {‘name’: ‘老坛酸菜泡面’, ‘price’: 3.5, ‘weight’: 300}
print(goods) # {‘name’: ‘老坛酸菜泡面’, ‘price’: 3.5, ‘weight’: 300}
goods.setdefault(‘count’, 100)
print(goods) # {‘name’: ‘老坛酸菜泡面’, ‘price’: 3.5, ‘weight’: 300, ‘count’: 100}
goods.setdefault(‘price’, 3)
print(goods) # {‘name’: ‘老坛酸菜泡面’, ‘price’: 3.5, ‘weight’: 300, ‘count’: 100}
练习:将没有折扣的商品的discount的值都设置成1
goods_list = [
{‘name’: ‘老坛酸菜泡面’, ‘price’: 3.5, ‘weight’: 300, ‘discount’: 0.8},
{‘name’: ‘牛奶’, ‘price’: 5, ‘weight’: 250},
{‘name’: ‘火腿肠’, ‘price’: 1.5, ‘weight’: 100},
{‘name’: ‘可乐’, ‘price’: 9, ‘weight’: 800, ‘discount’: 0.95}
]
for goods in goods_list:
goods.setdefault(‘discount’, 1)
print(goods_list)
2.删
- del 字典[键] - 删除指定键对应的键值对
- 字典.pop(键) - 取出指定键对应的值"“”
print(‘------------------------------------华丽的分割线-----------------------------------’)
dog = {‘name’: ‘财财’, ‘gender’: ‘母狗’, ‘breed’: ‘哈士奇’, ‘age’: 3}
print(dog)
del dog[‘breed’]
print(dog)
print(‘------------------------------------华丽的分割线-----------------------------------’)
dog = {‘name’: ‘财财’, ‘gender’: ‘母狗’, ‘breed’: ‘哈士奇’, ‘age’: 3}
print(dog)
x = dog.pop(‘age’)
print(dog, x) # {‘name’: ‘财财’, ‘gender’: ‘母狗’, ‘breed’: ‘哈士奇’} 3
4.字典的相关操作和方法
1.字典相关操作: in 和 not in
注意: 字典不支持:+、*、比较大小
字典的in和not in 判断的是是否存在指定的键
print(10 in {‘a’: 10, ‘b’: 20, ‘c’: 30}) # False
print(‘a’ in {‘a’: 10, ‘b’: 20, ‘c’: 30}) # True
2.字典相关函数: len、dict
补充:字典转换成列表的时候,是将字典的键作为列表的元素
dict1 = {‘a’: 10, ‘b’: 20, ‘c’: 30}
print(list(dict1)) # [‘a’, ‘b’, ‘c’]
dict(数据) - 将指定数据转换成字典
“”"
对数据的要求: a. 数据本身是一个序列
b. 序列中的元素必须是有两个元素的小序列
c. 小序列的第一个元素是不可变的类型的数据
print(dict([‘ab’, ‘cd’, ‘ef’])) # {‘a’: ‘b’, ‘c’: ‘d’, ‘e’: ‘f’}
print(dict([‘ab’, (10, 20), [‘age’, 18], range(2)])) # {‘a’: ‘b’, 10: 20, ‘age’: 18, 0: 1}
print(dict([(‘name’, ‘余婷’), (‘age’, 18), (‘gender’, ‘女’)])) # {‘name’: ‘余婷’, ‘age’: 18, ‘gender’: ‘女’}
3.字典相关方法: 字典.方法()
1)字典.clear() - 清空字典
2)字典.copy() - 拷贝原字典产生一个一模一样的新字典
3)
字典.keys() - 获取所有的键
字典.values() - 获取所有的值
字典.items() - 以元组的形式返回键值对
print(‘------------------------------------华丽的分割线-----------------------------------’)
dog = {‘name’: ‘财财’, ‘gender’: ‘母狗’, ‘breed’: ‘哈士奇’, ‘age’: 3}
print(dog.keys()) # dict_keys([‘name’, ‘gender’, ‘breed’, ‘age’])
print(dog.values()) # dict_values([‘财财’, ‘母狗’, ‘哈士奇’, 3])
print(dog.items()) # dict_items([(‘name’, ‘财财’), (‘gender’, ‘母狗’), (‘breed’, ‘哈士奇’), (‘age’, 3)])
print(‘------------------------------------华丽的分割线-----------------------------------’)
for key, value in dog.items():
print(key, value)
4.字典1.update(字典2) - 将字典2中所有的键值对都添加到字典1
dict1 = {‘a’: 10, ‘b’: 20, ‘c’: 30}
dict1.update({‘name’: ‘张三’, ‘age’: 19})
print(dict1) # {‘a’: 10, ‘b’: 20, ‘c’: 30, ‘name’: ‘张三’, ‘age’: 19}
5.列表推导式
字典推导式
“”"
结构1: {表达式1:表达式2 for 变量 in 序列}
结构2: {表达式1:表达式2 for 变量 in 序列 if 条件语句}
“”"
result = {x: x*2 for x in range(4)}
print(result) # {0: 0, 1: 2, 2: 4, 3: 6}
dog = {‘name’: ‘财财’, ‘gender’: ‘母狗’, ‘breed’: ‘哈士奇’, ‘age’: 3}
result = {x: None for x in dog}
print(result)
练习: 交换字典中所有的键值对键和值的位置
dict1 = {‘a’: 10, ‘b’: 20, ‘c’: 30}
{10:‘a’, 20:‘b’, 30:‘c’}
new_dict = {dict1[key]: key for key in dict1}
print(new_dict) # {10: ‘a’, 20: ‘b’, 30: ‘c’}
new_dict = {value: key for key, value in dict1.items()}
print(new_dict)