1.什么是字典(dict)
字典是容器型数据类型(序列),将{}大括号作为容器标志,里面多个元素用,逗号隔开(每个元素必须是键值对):
{键1:值1,键2:值2,键3:值3…}
字典是可变的(支持增删改);字典是无序的
键:不可变的数据才可以作为字典的键(数字、字符串、元组);键是唯一的
值:值才是字典真正想要保存的数据,键的作用是用来对值进行区分和说明的(类似于列表中下标);值可以使任何类型的数据。
1)空字典
dict1 = {}
print(dict1, type(dict1), len(dict1)) # {} <class 'dict'> 0
2)字典无序
print([1, 2, 3] == [3, 2, 1]) # False
print({'a': 10, 'b': 20} == {'b': 20, 'a': 10}) #True
3)键是不可变的
print({10: 20, 'abc': 30, (1, 2): 300})
print({10: 20, 'abc': 30, [1, 2]: 300}) # 报错
4)键是唯一的
print({10: 20, 'abc': 30, 10: 40, 'abc': 50}) # {10: 40, 'abc': 50}
1.查 - 获取值
1)查单个:
a. 字典[键] - 获取字典中指定键对应的值,键不存在会报错
b. 字典.get(键) - 获取字典中指定键对应的值,键不存在不会报错,但会返回None
c. 字典.get(键, 默认值) - 获取字典中指定键对应的值,键不存在不会报错,但会返回默认值
dog = {'name': '撒旦', 'breed': '土狗', 'gender': '母狗', 'age': 2}
print(dog['name']) # 撒旦
print(dog['age']) # 2
print(dog.get('breed')) # 土狗
print(dog['height']) # 报错
print(dog.get('height')) # None
print(dog.get('height', 40)) # 40
2)遍历
for 变量 in 字典:
循环体
dog = {'name': '撒旦', 'breed': '哈士奇', 'gender': '公狗', 'age': 5}
for i in dog:
print(i, dog[i])
list1 = [dog[i] for i in dog]
print(list1) # ['撒旦', '哈士奇', '公狗', 5]
2.增、改
字典[键] = 值 - 当键不存在的时候添加键值对,当键存在的时候修改指定键对应的值。
dog = {'name': '撒旦', 'breed': '哈士奇', 'gender': '公狗', 'age': 5}
dog['weight'] = 10
print(dog) #{'name': '撒旦', 'breed': '哈士奇', 'gender': '公狗', 'age': 5, 'weight': 10}
修改
dog['name'] = '傻蛋'
print(dog) # {'name': '傻蛋', 'breed': '哈士奇', 'gender': '公狗', 'age': 5, 'weight': 10}
3.删
1)del 字典[键] - 删除字典中指定键对应的键值对
dog = {'name': '撒旦', 'breed': '哈士奇', 'gender': '公狗', 'age': 5}
del dog['breed']
print(dog) # {'name': '撒旦', 'gender': '公狗', 'age': 5}
del dog['height'] # 报错
2)字典.pop(键) - 取出字典中指定键对应的值
dog = {'name': '撒旦', 'breed': '哈士奇', 'gender': '公狗', 'age': 5}
del_val = dog.pop('gender')
print(dog) # {'name': '撒旦', 'breed': '哈士奇', 'age': 5}
print(del_val) # 公狗
练习:写程序交换字典的键和值
dict1 = {'a': 'b', 'c': 'd', 'e': 'f'}
dict2 = {}
for i in dict1:
dict2[dict1[i]] = i
print(dict2) # {'b': 'a', 'd': 'c', 'f': 'e'}
方法2:
dict3 = {dict1[i]: i for i in dict1}
print(dict3) # {'b': 'a', 'd': 'c', 'f': 'e'}
练习:使用推导式产生一个字典:
{2:4, 3:6, 4:8, 5:10}
{2:22, 3:33, 4:44, 5:55}
dict1 = {i: i*2 for i in range(2, 6)}
print(dict1) # {2: 4, 3: 6, 4: 8, 5: 10}
dict2 = {i: i*11 for i in range(2, 6)}
print(dict2) # {2: 22, 3: 33, 4: 44, 5: 55}
dict2 = {str(i): i*11 for i in range(2, 6)}
print(dict2) # {'2': 22, '3': 33, '4': 44, '5': 55}
1.运算符
字典不支持比较运算(比较大小)和数学运算
print([1, 2, 3, 4, 5] > [10, 20]) # False,比较第一对不相等的元素的大小:1 < 10
#print({'a': 10} > {'a': 20}) # 报错
#print({'a': 10} + {'a': 20}) # 报错
2.in 和 not in
键 in 字典 - 判断字典中是否存在指定键对应的键值对
键 not in 字典 - 判断字典中是否不存在指定键对应的键值对
cat = {'name': '猫爷', 'color': '黑色', 'breed': '田园'}
print('猫爷' in cat) # False
print('name' in cat) # True
3.相关函数:len、dict
print(len(cat)) # 3
dict(数据) - 将指定数据转换成字典。
数据的要求:1.数据本身是一个序列;2.序列中的元素必须是有且只有两个元素的小序列;
3.小序列中的第一个元素必须是不可变的数据
list1 = [(10, 20), 'ab']
result = dict(list1)
print(result) # {10: 20, 'a': 'b'}
result = dict((i, i*2)for i in range(3))
print(result) # {0: 0, 1: 2, 2: 4}
字典转其他序列
cat = {'name': '猫爷', 'color': '黑色', 'breed': '田园'}
print(list(cat)) # ['name', 'color', 'breed']
print(tuple(cat)) # ('name', 'color', 'breed')
4.字典相关方法
1)字典.clear()
cat.clear()
print(cat)
2)字典.copy()
cat = {'name': '猫爷', 'color': '黑色', 'breed': '田园'}
cat1 = cat.copy()
print(cat1)
3)keys、values、items
字典.keys() - 获取字典所有的键,返回值是序列
字典.values() - 获取字典所有的值,返回值是序列
字典.items() - 将字典转换成元素是元组的序列(一个键值对应一个元组)
print(cat.keys()) # dict_keys(['name', 'color', 'breed'])
print(cat.values()) # dict_values(['猫爷', '黑色', '田园'])
print(cat.items()) # dict_items([('name', '猫爷'), ('color', '黑色'), ('breed', '田园')])
for x, y in cat.items():
print(x, y)
4)字典.setdefault(键, 值) - 添加键值对(键存在的时候不会修改)
cat = {'name': '猫爷', 'color': '黑色', 'breed': '田园'}
cat.setdefault('weight', 10)
print(cat) # {'name': '猫爷', 'color': '黑色', 'breed': '田园', 'weight': 10}
cat.setdefault('color', '白色')
print(cat) # {'name': '猫爷', 'color': '黑色', 'breed': '田园', 'weight': 10}
5)字典.update(序列) - 将序列中的元素添加到字典中(序列必须是可以转换成字典的序列)
字典1.update(字典2) - 将字典2中所有的键值对添加到字典1中
更新的序列中如果有原字典已经存在的键,则更新键对应的值
cat = {'name': '猫爷', 'color': '黑色', 'breed': '田园'}
cat.update([(10, 20), 'ab'])
print(cat) # {'name': '猫爷', 'color': '黑色', 'breed': '田园', 10: 20, 'a': 'b'}
cat = {'name': '猫爷', 'color': '黑色', 'breed': '田园'}
cat.update({'a': 'b', 'color': '白色'})
print(cat) # {'name': '猫爷', 'color': '白色', 'breed': '田园', 'a': 'b'}
1.实际开发中的字典
cl = {
'name': 'python2103',
'address': '6教室',
'students': [
{'name': 'stu1',
'age': 20,
'tel': '114511',
'gender': '男',
'linkman': {'name': '老大', 'tel': '1551'}},
{'name': 'stu2',
'age': 22,
'tel': '114512',
'gender': '男',
'linkman': {'name': '老二', 'tel': '1552'}},
{'name': 'stu3',
'age': 23,
'tel': '114513',
'gender': '男',
'linkman': {'name': '老三', 'tel': '1553'}},
{'name': 'stu4',
'age': 24,
'tel': '114514',
'gender': '男',
'linkman': {'name': '小明', 'tel': '1554'}}
],
'teachers': [
{'name': '余婷', 'job': '讲师', 'QQ': '645695'},
{'name': '舒玲', 'job': '班主任', 'QQ': '8272129'}
]
}
练习:
打印所有学生的紧急联系人的电话
打印所有老师的名字
给所有的紧急联系人添加性别,性别默认是男
for i in cl['students']:
print(i['linkman']['tel'])
for i in cl['teachers']:
print(i['name'])
for i in cl['students']:
# i['linkman']['gender'] = '男'
# i['linkman'].setdefault('gender', '男')
i['linkman'].update({'gender': '男'})
print(i['linkman'])
1.什么是集合(set)
集合是容器型数据类型(序列),将{}大括号作为容器标志,里面多个元素用逗号隔开:{元素1, 元素2, 元素3,…}
集合是可变的(支持增删改);无序的(不支持下标)
集合中的元素:必须是不可变的数据;唯一的数据
1)空集合
set1 = set()
print(set1, type(set1), len(set1)) # set() <class 'set'> 0
2)集合无序
print({1, 2, 3} == {3, 2, 1}) # True
3)集合的元素是不可变的数据
print({10, 'abc', (2, 3)}) # {(2, 3), 10, 'abc'}
#print({10, 'abc', [2, 3]}) # 报错
4)集合元素是唯一的
print({10, 20, 30, 10, 20, 10}) # {10, 20, 30}
print(list({10, 20, 30, 10, 20, 10})) # [10, 20, 30]
2.集合的增删改查
1)查 - 只有遍历
nums = {10, 78, 67, 35, 70, 89}
for i in nums:
print(i)
2)增
集合.add(元素) - 在集合中添加指定元素
集合.update(序列) - 将序列中所有的元素都添加到集合中
nums = {10, 78, 67, 35, 70, 89}
nums.add(100)
print(nums) # {35, 67, 100, 70, 10, 78, 89}
nums = {10, 78, 67, 35, 70, 89}
nums.update('abc')
print(nums) # {35, 67, 'c', 70, 10, 'b', 78, 89, 'a'}
nums = {10, 78, 67, 35, 70, 89}
nums.update({'name': '张三', 'age': 18})
print(nums) # {35, 67, 70, 10, 78, 'name', 89, 'age'}
3)删
集合.remove(集合) - 删除指定元素,元素不存在会报错
集合.discard(元素) - 删除指定元素,元素不存在不会报错
nums = {10, 78, 67, 35, 70, 89}
nums.remove(10)
print(nums) # {35, 67, 70, 78, 89}
nums.discard(35)
print(nums) # {67, 70, 78, 89}
#nums.remove(100) # 报错
nums.discard(100)
数学集合运算:&(交集)、|(并集)、-(差集)、^(对称差集)、><(判断是否是真子集)、>=<=(判断是否是子集)
1.集合1 & 集合2 - 交集(获取两个集合公共部分)
set1 = {1, 2, 3, 4, 5, 6}
set2 = {4, 5, 6, 7, 8}
print(set1 & set2) # {4, 5, 6}
2.集合1|集合2 - 并集(将两个集合合并产生一个新的集合)
print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7, 8}
set3 = set1 | set2
print(set3) # {1, 2, 3, 4, 5, 6, 7, 8}
3.集合1 - 集合2 - 差集(获取集合1中除了包含在集合2中以外的元素)
print(set1 - set2) # {1, 2, 3}
print(set2 - set1) # {8, 7}
4.集合1 ^ 集合2 - 对称差集(集合1和集合2合并然后去掉公共部分)
print(set1 ^ set2) # {1, 2, 3, 7, 8}
5.子集
集合1 > 集合2 - 判断集合2是否是集合1的真子集
集合1 >= 集合2 - 判断集合2是否是集合1的子集
print({10, 20, 30, 40} > {1, 2}) # False
print({10, 20, 30, 40} > {10, 20}) # True
print({10, 20} > {10, 20}) # False
print({10, 20} >= {10, 20}) # True
{1, 2, 3} 的真子集:{}、{1}、{2}、{3}、{1, 2}、{1, 3}、{2, 3}
{1, 2, 3} 的子集:{}、{1}、{2}、{3}、{1, 2}、{1, 3}、{2, 3}、{1, 2, 3}
6.python中数字相关的类型有4种:int、float、bool、complex
True == 1 、 False == 0
1.complex - 复数
python中复数的格式: a + bj (j是虚数单位,j**2 == -1、b是1的时候不能省)
a = 10 + 2j
print(a, type(a)) # (10+2j) <class 'complex'>
python的复数直接支持复数运算
b = 5 - 6j
print(a + b) # (15-4j)
print(a * b) # (62-50j)
2.数学模块
import math # 导入浮点数的数学运算函数
import cmath # 导入复数运算的函数
将浮点数转换成整数
1)int(浮点数)
num = -3.95
print(int(num)) # -3
2)math.ceil(浮点数) - 向大取整
print(math.ceil(1.99)) # 2
print(math.ceil(1.29)) # 2
print(math.ceil(2.001)) # 3
print(math.ceil(-3.0001)) # -3
3)math.floor(浮点数)
print(math.floor(1.99)) # 1
print(math.floor(1.001)) # 1
print(math.floor(-2.999)) # -3
4)round(浮点数)
print(round(2.999)) # 3
print(round(2.11)) # 2
print(round(-3.51)) # -4
print(round(-2.49)) # -2
2.2 math.fabs(数字) - 返回数字的绝对值,结果为浮点数
print(math.fabs(-23)) # 23.0
print(math.fabs(12)) # 12.0
abs(数字) - 获取数字的绝对值
print(abs(-23)) # 23
print(abs(-2.23)) # 2.23
作业
- 用三个集合表示三门学科的选课学生姓名(一个学生可以同时选多门课)
- 求选课学生总共有多少人
- 求只选了第一个学科的人的数量和对应的名字
- 求只选了一门学科的学生的数量和对应的名字
- 求只选了两门学科的学生的数量和对应的名字
- 求选了三门学生的学生的数量和对应的名字
history = {'老大', '老二', '老三', '老四', '老五', '老六'}
music = {'老三', '老四', '老五', '老六', '老七', '老八'}
art = {'老大', '老六', '老七', '老八', '老九', '小明'}
# 1.
result1 = history | music | art
print('选课学生人数总共有:', len(result1))
# 2.
result2 = history-music-art
print('只选了第一门学科的人数为:', len(result2), '名字是:', result2)
# 3.
result4 = history & music & art
result3 = history ^ music ^ art
print('只选了一门学科的人数为:', len(result3 - result4), '名字是:', result3 - result4)
# 4.
result = result1 - result3 - result4
print('只选了两门学科的学生的数量为:', len(result), '名字是:', result)
# 5.
print('选了三门学科的学生的数量为:', len(result4), '名字是:', result4)
"""
Time:2021/5/7 0007 下午 7:19
Author:教徒
"""
stu_list = []
count = 1
while True:
print('''❤1.添加学生
❤2.查看学生
❤3.修改学生信息
❤4.删除学生
❤5.结束''')
inp_num = int(input('请选择(1-5):'))
if inp_num == 1:
while True:
stu_dict = {}
stu_name = input('请输入学生姓名:')
stu_age = input('请输入学生的年龄:')
stu_tel = input('请输入学生的电话:')
stu_dict['stu_num'] = 'stu00' + str(count)
stu_dict['name'] = stu_name
stu_dict['age'] = stu_age
stu_dict['tel'] = stu_tel
stu_list.append(stu_dict)
count += 1
print('添加成功!')
inp_num1 = int(input('''1.继续
2.返回
请选择(1-2):'''))
if inp_num1 == 2:
break
if inp_num == 2:
for i in stu_list:
print('学号:', i['stu_num'], '姓名:', i['name'], '年龄:', i['age'], '电话', i['tel'])
elif inp_num == 3:
stu_num = input('请输入要修改学生的学号:')
for i in stu_list:
if i['stu_num'] == stu_num:
stu_name = input('请输入新的学生姓名:')
stu_age = input('请输入新的学生的年龄:')
stu_tel = input('请输入新的学生的电话:')
i['name'] = stu_name
i['age'] = stu_age
i['tel'] = stu_tel
print('修改完成了!')
break
elif inp_num == 4:
while True:
print('1.开始删除')
print('2.返回')
inp_num = int(input('请选择1-2:'))
if inp_num == 1:
stu_num = input('请输入需要删除学生的学号:')
for i in stu_list:
if i['stu_num'] == stu_num:
stu_list.remove(i)
print('删除成功!')
break
else:
print('学号错误!请重新输入')
else:
break
elif inp_num == 5:
print('结束啦!~')
break
else:
continue