0
点赞
收藏
分享

微信扫一扫

day8-字典作业(1)

窗外路过了谁 2022-02-23 阅读 30
python

day8-字典

1.认识字典

1.字典和列表的选择:

需要同时保存多个数据的时候,如果多个数据的意义相同(不需要区分)就使用列表;如果多个数据的意义不同就使用字典

2.认识字典(dict)

1)是容器型数据类型;
将{}作为容器的标志,里面多个键值对用逗号隔开:{键1:值1,键2:值2,键3:值3,…}
键值对的格式:键:值

2)特点
字典是可变的(支持增删改);字典是无序(不支持下标,元素顺序不影响结果)

3)对元素的要求
字典的元素是键值对
a. 键的要求:键必须是不可变的类型的数据(数字、字符串、布尔、元组等);键是唯一的
b. 值的要求:没有要求

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
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': 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) 获取班级名字
print(class1['name'])
# 2) 获取讲师的名字
print(class1['lecturer']['name'])
# 3) 获取班主任电话号码
print(class1['class_teacher']['tel'])
# 4) 统计学生中男生的数量
count = 0
for x in class1.get('students'):
    if x['gender'] == '男':
        count += 1
print(count)
# 5) 计算所有学生分数的平均分
# 方法一
avg = 0
count = 0
for x in class1['students']:
    avg += x['score']
    count += 1
print(avg / count)

# 方法2
all_student = class1['students']
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)

# 方法2:
# 假设第一个学生分数最高
all = class1['students']
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) 获取所有紧急联系人的电话
nums = []
for x in class1.get('students'):
    nums.append(x.get('linkman')['tel'])
print(nums)
3.遍历
"""
1)直接遍历
for 键 in 字典:
    pass 
    
2)
for 键,值 in 字典.items():
    pass
"""
stu = {'name': '小明', 'gender': '男', 'age': 18, 'score': 100, 'education': '专科'}
for x in stu:
    print(x, stu[x])
    
for key, value in stu.items():
    print(key, value)

3.字典增删改

1.增/改 - 添加键值对
"""
1)字典[键] = 值    如果键存在就修改指定对应的值;如果键不存在就添加键值对

2)字典.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', 2000)
print(cat)     # {'name': '小白', 'breed': '加菲', 'color': '白色', 'age': 2, 'price': 2000}
2.删 - 删除键值对
"""
del 字典[键]    -    删除指定键对应的键值对
字典.pop(键)    -    取出指定键对应的值
"""
cat = {'name': '花花', 'breed': '加菲', 'color': '白色'}
del cat['breed']
print(cat)

result = cat.pop('color')
print(cat, result)   # {'name': '花花'} 白色

4.字典相关操作函数和方法

1.相关操作
1.字典不支持: +*><>=<=,只支持: ==!=
2.innot in   -    字典的innot in操作判断的是字典中是否存在指定的键
键 in 字典

dict1 = {'a': 10, 'b': 20, 'c': 30}
print(10 in dict1)   # False
print('a' in dict1)   # True

3.相关函数:lendict
"""
a. len(字典)  -  获取字典中键值对的个数

b. dict(数据)  -  将指定数据转换成字典
对数据的要求:1.数据本身是一个序列
           2.序列中的元素必须都是有且只有两个元素的小序列,并且其中第一个元素是不可变的数据
"""

print(len(dict1))

seq = ['ab', 'cd', 'ef']
print(dict(seq))

4.相关方法
# a. 字典.clear()
# b. 字典.copy()
dog = {'name': '大黄', 'breed': '土狗', 'gender': '母狗'}
dog1 = dog
dog2 = dog.copy()
print(dog1, dog2)

# c.
# 字典.keys()  -  返回一个序列,序列中的元素是字典所有的键
# 字典.value()  -  返回一个序列,序列中的元素是字典所有的值
# 字典.items()  -  返回一个序列,序列中的元素是由每一对键和值组成的元组
print(dog.keys())     # dict_keys(['name', 'breed', 'gender'])
print(dog.values())   # dict_values(['财财', '土狗', '母狗'])
print(dog.items())    # dict_items([('name', '财财'), ('breed', '土狗'), ('gender', '母狗')])

# d.update
# 字典.update(序列)  -  将可以序列中的元素全部添加字典中(序列必须是可以转换成字典的序列)
# 字典1.update(字典2)  -  将字典2中所有的键值对都添加到字典1中
dict1 = {'a': 10, 'b': 20}
dict2 = {'c': 100, 'd': 200, 'a': 1000}
dict1.update(dict2)
print(dict1)

5.字典推导式

字典推导式
“”"
{表达式1:表达式2 for 变量 in 序列}
{表达式1:表达式2 for 变量 in 序列 if 条件语句}
“”"

result = {x: x*2 for x in range(5)}
print(result)

result = {x: x for x in range(10) if x % 3}
print(result)

作业

  1. 定义一个变量保存一个学生的信息,学生信心中包括:姓名、年龄、成绩(单科)、电话、性别

    dict1 = {'name': 'lth', 'age': 18, 'score': '98', 'tel': '18944545', 'gender': '男'}
    
  2. 定义一个列表,在列表中保存6个学生的信息(学生信息中包括: 姓名、年龄、成绩(单科)、电话、性别(男、女、不明) )

    students = [
        {'name': '小明', 'age': 18, 'score': 100, 'tel': '110428228', 'gender': '男'},
        {'name': '小花', 'age': 20, 'score': 43, 'tel': '1208282748', 'gender': '女'},
        {'name': '张三', 'age': 30, 'score': 90, 'tel': '1324534340', 'gender': '不明'},
        {'name': '李四', 'age': 22, 'score': 56, 'tel': '1405445448', 'gender': '不明'},
    	{'name': '王二', 'age': 28, 'score': 95, 'tel': '1542453440', 'gender': '不明'},
        {'name': '赵敏', 'age': 27, 'score': 100, 'tel': '1603435343', 'gender': '女'},
    ]
    
    1. 统计不及格学生的个数

      count = 0
      for x in students:
          if x['score'] < 60:
              count += 1
      print(count)
      
    2. 打印不及格未成年学生的名字和对应的成绩

      for x in students:
          if x['score'] < 60 and x['age'] < 18:
              print(x['score'],x['name'])
      
    3. 求所有男生的平均年龄

      sum = 0
      count = 0
      for x in students:
          if x['gender'] == '男':
              sum += x['score']
              count += 1
            
      result = sum / count
      print(result)
      
    4. 打印手机尾号是8的学生的名字

      print([x['name'] for x in students if x['tel'][-1] == '8'])
      
    5. 打印最高分和对应的学生的名字

      max_score = max(stu['score'] for stu in students)
      for x in students:
          if x['score'] == max_score:
              print(x['score'], x['name'])
      
    6. 删除性别不明的所有学生

      x = 0
      while x < len(students):
          if students[x]['gender'] == '不明':
              students.remove(students[x])
          else:
              x += 1
      print(students)
      
    7. 将列表按学生成绩从大到小排序(挣扎一下,不行就放弃)

  3. 定义一个变量保存一个班级的信息,班级信息中包括:班级名称、教室位置、班主任信息、讲师信息、班级所有的学生(根据实际情况确定数据类型和具体信息)

    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': '专科'},
            {'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': 95, 'education': '本科'},
            {'name': '赵敏', 'gender': '女', 'age': 27, 'score': 99, 'education': '专科'},
            {'name': '老王', 'gender': '男', 'age': 22, 'score': 89, 'education': '本科'}
        ]
    }
    
    
  4. 已知一个列表保存了多个狗对应的字典:

    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': '母'}
    ]
    
    1. 利用列表推导式获取所有狗的品种

      print([x['breed'] for x in dogs])
      
    2. 利用列表推导式获取所有白色狗的名字

      print([x['name'] for x in fogs if x['color'] == '白色'])
      
    3. 给dogs中没有性别的狗添加性别为 ‘公’

      for x in dogs:
              x.setdefault('gender', '公')
      print(dogs)
      
    4. 统计 ‘银狐’ 的数量

      count = 0
      for x in dogs:
          if x['breed'] == '银狐':
              count += 1
      print(count)
      
举报

相关推荐

0 条评论