字典和集合
- 字典
1.字典存在的价值 - 可以在同时保存多个意义不同的数据的时候通过key来对数据进行区分和说明
stu = {'姓名': '小明', 'age': 30, 'tel': '110', 'score': 80, '体重': 90}
print(stu['姓名'])
2.什么是字典(dict)
字典是容器型数据类型;将{}作为容器的标志,里面多个元素(元素是键值对)用逗号隔开:{键1:值1,键2:值2…}
字典的元素:必须是键值对;
键 - 必须是不可变数据,一般用字符串;唯一的(功能是对值进行说明)
值 - 任何类型的数据都可以,可以重复(值才是字典真正想要保存的数据)
字典是可变的(支持增删改);字典是无序的(不支持下标)
d1 = {} # 空字典
print(type(d1), d1)
# 键不可变
d2 = {'abc':100, 12:100, (10,20):300}
print(d2)
# d3 = {'abc':100, 12:100, [10,20]:300} # TypeError: unhashable type: 'list' 列表不能作为key
# 键是唯一的
d4 = {'name': '小明', 'name': '小花', 'age': 18}
print(d4)
# 值是任何类型的数据
d5 = {'k1':90, 'k2':1.23, 'k3':True, 'k4':'abc', 'k5':[1,2], 'k6':{'a':10}, 'k7':lambda x:x*2}
print(d5)
# 字典无序
d6 = {'name': '张三', 'age': 30}
d7 = {'age': 30, 'name': '张三'}
print(d6 == d7)
- 字典中元素的增删改查
1.查 - 获取字典的值
- 查单个值
字典[key] - 获取字典中指定key对应的值
字典.get(key) - 获取字典中指定key对应的值
字典.get(key, 默认值) - 获取字典中指定key对应的值;如果不存在,返回默认值
dog = {'name': '旺财', '性别': '公狗', 'color': '黄色', 'breed': '土狗', 'age':2}
print(dog['name'], dog['breed'])
# print(dog['height']) # KeyError: 'height'
print(dog.get('name'))
print(dog.get('height')) # None
print(dog.get('color', '黑色')) # 黄色
print(dog.get('height', 0)) # 0
- 遍历
for 变量 in 字典:
循环体
注意:变量取到的是字典的每个key
dog = {'name': '旺财', '性别': '公狗', 'color': '黄色', 'breed': '土狗', 'age':2}
for x in dog:
print('x:', x, dog[x])
# 练习:
# 1)统计班级中不及格学生的人数
# 2)计算所有学生的平均分
classes = [
{'name': '小明', 'age': 26, 'score': 90, 'sex': '男'},
{'name': 'stu1', 'age': 13, 'score': 89, 'sex': '女'},
{'name': 'stu2', 'age': 22, 'score': 77, 'sex': '女'},
{'name': 'stu3', 'age': 34, 'score': 56, 'sex': '男'},
{'name': 'stu4', 'age': 15, 'score': 34, 'sex': '女'},
{'name': 'stu5', 'age': 20, 'score': 70, 'sex': '男'},
]
num ,sum1= 0, 0
for x in classes:
if x['score'] < 60:
num += 1
sum1 += x['score']
print('不及格人数:', num, '平均分:', sum1/len(classes))
2.增/改 - 添加键值对/修改键对应的值
1)字典[key] = 值 - 如果key存在就是添加 key:值 对应的键值对;如果key存在就是修改指定key存在的值
computer = {'brand': '联想', 'color': '灰色', 'price': 5300, 'ram': 16}
# 增加
computer['cpu_num'] = 4
print(computer)
# 修改
computer['color'] = '黑色'
print(computer)
2)字典.setdefault(key, value) - 添加键值对(只能添加不能修改)
computer.setdefault('size', 14)
print(computer)
computer.setdefault('price', 3000)
print(computer)
3.删 - 删除键值对
- del 字典[key] - 删除指定key对应的键值对(如果指定key不存在会报错
computer = {'brand': '联想', 'color': '灰色', 'price': 5300, 'ram': 16}
del computer['ram']
print(computer)
2)字典.pop(key) - 取出指定key的值,并且返回key对应的值
color = computer.pop('color')
print(computer)
print(color)
- 字典相关操作
1.运算符
字典不支持+、*、>、<、>=、<=, 只支持==和!=
d1 = {'a': 10, 'b': 20}
d2 = {'b': 20, 'a': 10}
print(d1 == d2)
2.in和not in
key in 字典 - 判断字典中是否存在指定的key
d3 = {'a': 10, 'b': 20, 'c': 30}
print('a' in d3)
3.相关函数
# (了解)sum,max,min,sorted - 针对的操作对象是字典的key
print(sum({10:1, 20:2, 30:3})) # 60
# len,dict
# len(字典) - 获取字典中键值对的个数
d3 = {'a': 10, 'b': 20, 'c': 30, 100:200}
print(len(d3)) # 4
# dict(数据) - 将指定数据转换成字典
# 数据 - a.数据本身是序列 b.序列中的每一个元素是小序列 c.小序列中元素的个数是2 d.小序列的第一个元素不可变
seq = [(1, 2),(10, 20),(100, 200),(1000, 2000),('abc', 123),'ab']
d4 = dict(seq)
print(d4) # {1: 2, 10: 20, 100: 200, 1000: 2000, 'abc': 123, 'a': 'b'}
# 字典转列表
computer = {'brand': '联想', 'color': '灰色', 'price': 5300, 'ram': 16}
print(list(computer)) # ['brand', 'color', 'price', 'ram']
- 字典的相关方法
1.字典.clear() - 清空字典
2.字典.copy() - 赋值字典产生一个一模一样的新字典并返回
p1 = {'name': '小明', 'age': 18, 'gender':'男'}
p2 = p1
p3 = p1.copy()
print(p2)
print(p3)
p1['name'] = '小花'
print(p2)
print(p3)
3.dict.fromkeys(序列, 值) - 创建一个新的字典,将序列中的元素作为字典的key,
每一个key对应的值就是指定值
# dict.fromkeys(序列)
d1 = dict.fromkeys('abc', 100)
print(d1) # {'a': 100, 'b': 100, 'c': 100}
d2 = dict.fromkeys(['name','age','sex'])
print(d2) # {'name': None, 'age': None, 'sex': None}
d3 = dict.fromkeys(['name','age','sex'],0)
print(d3) # {'name': 0, 'age': 0, 'sex': 0}
4.字典.items() - 同时获取字典的key和值 将字典转换成一个序列,序列中的元素是每个键值对对应的小序列
student = {'name':'小明', 'age':18, 'gender':'男', 'score':90}
print(student.items()) # dict_items([('name', '小明'), ('age', 18), ('gender', '男'), ('score', 90)])
print(list(student.items())) # [('name', '小明'), ('age', 18), ('gender', '男'), ('score', 90)]
# 遍历字典的时候同时获取键和值(效率低)
for key, value in student.items():
print(key, value)
# 练习:通过列表推导式交换一个字典的key和value的位置
# d3 = {'a': 10, 'b': 20, 'c': 30}
d1 = {'a': 10, 'b': 20, 'c': 30}
list1 = [(y,x) for x,y in d1.items()]
d2 = dict(list1)
print(d2)
5.字典.keys() - 获取字典所有的key
print(d1.keys())
6.字典.values() - 获取字典中所有的值(返回一个序列)
print(d1.values())
7.字典.update(序列) - 将序列中的元素以键值对的形式添加到字典里面
序列:必须是可以转换成字典的序列
d1.update({100:200,20:30})
print(d1)
- 集合
1.什么是集合
容器:将{}作为容器的标志,多个元素用逗号隔开:{元素1,元素2,元素3…}
元素:不可变的;唯一的
可变的;无序的
1)空集合
s1 = {} # {}是空字典不是空集合
print(type(s1)) # <class 'dict'>
s2 = set()
print(type(s2), len(s2)) # <class 'set'> 0
2)集合元素不可变
s3 = {90, 'abc', (1, 2)}
print(s3)
# s4 = {90, 'abc', [1, 2]} # TypeError: unhashable type: 'list'
3)集合元素是唯一的
s5 = {1,2,3,1,1,2}
print(s5)
l1 = ['张三','李四','张三','隔壁老王', '李四', '张三']
new_l1 = list(set(l1))
print(new_l1)
2.数学集合运算:并集(|)、交集(&)、差集(-)、对称差集(^)、子集(>=)、真子集(>)
A = {1,2,3,4,5,6}
B = {4,5,6,7,8}
# 1)并集 - A和B的并集是将A和B的元素放到一起构成的新集合
C = A | B
print(C) # {1, 2, 3, 4, 5, 6, 7, 8}
# 2)A和B的交集,写作A&B,是既属于A的、又属于B的所有元素组成的集合。
C = A & B
print(C) # {4, 5, 6}
# 3)差集 - 两个集合也可以相"减"。写作B−A,是属于B的、但不属于A的所有元素组成的集合
C = B - A
print(C) # {8, 7}
C = A - B
print(C) # {1, 2, 3}
# 4)对称差集 - 在集合A和集合B中,只包含在A中和只包含在B中的元素的集合
C = A ^ B
print(C) # {1, 2, 3, 7, 8}
# 5)子集: >= 判断是否为子集 > 判断是否为真子集
A = {1,2,3,4,5}
B = {4,5}
print(A >= B) # True
print(A > B) # False
C = {4,5}
print(B >= C) # True
print(B > C) # False
D = {1,7}
print(A > D) # False