总结day008
认识字典
- 字典和列表的选择:
# 需要同时保存多个数据的时候,如果多个数据意义相同(不需要区分)就使用列表;如果多个数据的意义不同就使用字典
- 认识字典(dict)
# 1)
是容器型数据类型;将{}作为容器的标志,里面多个键值对用逗号隔开。{键1:值1, 键2:值2 , 键3:值3 ,...}
键值对的格式: key:value 键:值
# 2) 特点
字典是可变的(支持增删改);字典是无序的(不支持下标,元素顺序不影响结果)
# 3)对元素的要求
字典的元素是键值对
a. 键的要求:键必须是不可变的类型的数据(数字、字符串、布尔、元组);键是唯一的
b. 值得要求: 没有要求
空字典
dict1 = {}
# 字典中的元素只能是键值对
dict2 = {'name':'小明', 'age':'20'}
# dict3 = {'name':'小二', 30} - 报错
# 字典是可变的(支持增删改);字典是无序的(不支持下标,元素顺序不影响结果)
print({'a':'123','b':'234'}=={'b':'234','a':'123'})
# 键是不可变类型的数据
dict1 = {'str1':'12',1:2,(1,):4}
# dict1 = {'str1':'12',1:2,[1,2]:4} - 报错
#键是唯一的
字典基本操作
- 查 - 获取字典的值
# 1)查单个 - 一次获取一个值
'''
语法1:字典[键] - 获取字典中指定键对应的值,获取不存在的键会报错
语法2: 字典.get(键) - 获取字典中键对应的值,获取不存在的键不会报错,并且返回None
字典.get(键,默认值) - 如果键不存在,返回默认值
'''
dog = {'name':'旺财','age':3, 'breed':'中华田园犬','color':'白色'}
print(dog['age'])
print(dog['name'])
print(dog.get('name'))
- 列表和字典正确的打开方式
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': 95, '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) 获取班级名字
# for i in class1:
print(class1['name'])
# 2) 获取讲师的名字
# for key in class1['class_teacher']:
# print(key['name'])
print(class1['class_teacher']['name'])
# 3) 获取班主任电话号码
print(class1['class_teacher']['tel'])
# 4) 统计学生中男生的数量
count = 0
for i in class1['students']:
if i['gender'] == '男':
count+=1
print(count)
# 5) 计算所有学生分数的平均分
sum = 0
for i in class1['students']:
sum += i['score']
print(sum/len(class1['students']))
# 6) 获取分数最高的学生的名字
all = class1['students']
max_sc = max(stu['score'] for stu in all)
print(max_sc)
names = [stu['name'] for stu in all if stu['score']==max_sc]
print(names)
-------------------------------------------------
a=[i['score'] for i in class1['students']]
b=[i['name'] for i in class1['students']]
print(b[a.index((max(a)))])
# 方法2:
#假设第一个学生的分数最高
max_sc = all[0]['score']
names = [all[0]['name']]
for stu in all[1:]:
score = stu['score']
if score > max_sc:
max_sc =score
names.clear()
names.append(stu['name'])
elif score == max_sc:
names.append(stu['name'])
print(max_sc,names)
# 7) 获取所有紧急联系人的电话
# for i in class1['students']:
# print(i['linkman']['tel'])
遍历
1)直接遍历
for 变量 in 字典:
pass
'''
stu = {'name':'xi','gender':'yu','age':'18'}
for i in stu:
print(i,stu[i])
'''
# 2)
for 键,值 in 字典.items():
pass
for key, value in stu.items():
print(key,value)
字典增删改
- 增/改 - 添加键值对
#1)字典[键] = 值 如果键存在就修改指定键对应的值;如果键不存在就添加键值对
#2) 字典.setdefault(键,值) 添加键值对(如果键不存在添加,存在不添加不修改)
cat = {'name':'wangkeyu','breed':'加菲猫','color':'heiabi'}
print(cat)
# 修改
cat['name'] = '小白'
print(cat)
- 删 - 删除键值对
del 字典[键] - 删除指定键对应的键值对
字典.pop(键) - 取出指定键对应的值
字典相关操作函数和方法
- 相关操作
# 1)字典不支持: + , * , > , < ,<= ,>= ,只支持 == , !=
# 2) in 和 not in - 字典的in 和 not in操作判断的是字典中是否存在指定的键
# 键 in 字典
dict1 = {'a':10,'b':20,'c':30}
print(10 in dict1) # False
print('a' in dict1) # True
- 相关函数:len、dict
# a. len(字典) - 获取字典中键值对的个数
print(len(dict1))
# b. dict(数据) - 将指定数据转换成字典
# 对数据的要求:1,数据本身是一个序列
#2,序列的元素必须都是有且只有两个元素的小序列,并且其中一个元素是不可变的数据
seb = ['ab','ef','cd']
print(dict(seb))
seq = [(10,20),range(2),'he']
print(dict(seq))
- 相关方法
# a. 字典.clear()
# b. 字典.copy()
# c.
# 字典.keys()
# 字典.values()
# 字典.items()
dog = {'xia':'12','as':'15','ll':'11'}
print(dog.keys(),type(dog.keys()))
print(dog.items())
# d. update
# 字典.update(序列) - 将序列中的元素全部添加字典中(序列必须是可以转换成字典的序列)
# 字典1.uodate(字典2) - 将字典2中所有的键值对全都添加到字典1中
dict1 = {'a':10,'b':20}
dict2 = {'c':100,'d':200}
dict2 = ['ab']
dict1.update(dict2)
print(dict1)
字典表达式
{表达式1:表达式2 for 变量 in 序列}
{表达式1:表达式2 for 变量 in 序列 if 条件语句}
resul = {i:i*2 for i in range(5)}
print(resul)
resul = {i:i for i in range(10) if i % 3}