day8 - 字典

day 8 字典

1、字典和列表的选择

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

2、认识字典

1、是容器型数据类型

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

2、作为容器的特点

1、字典是可变的(支持增删改)
2、字典是无序的(不支持下标操作,元素顺序不影响结果)

3、对元素的要求 - 字典的元素是键值对

1、键的要求:键必须是不可变的类型的数据(数字、字符串、布尔、元组等);键是唯一的
2、值的要求:没有要求

# 1.空字典	-	是有意义的,因为字典是可变的
dict1 = {}

# 字典中的元素只能是键值对
dict2 = {'name': '板栗', 'age': 3}
print(dict2)                    # {'name': '板栗', 'age': 3}

# 2.字典无序
print({'a': 1, 'b': 2} == {'b': 2, 'a': 1})         # True

# 键是不可变类型的数据
dict3 = {10: 23, 1.23: 10, 'abc': 30, (1, 2): 50}
print(dict3)                # {10: 23, 1.23: 10, 'abc': 30, (1, 2): 50}

# dict3 = {10:23, 1.23: 10, 'abc': 30, [1, 2]: 50}
# print(dict3)                # 键可变,程序报错

# 键是唯一的
dict3 = {10: 23, 1.23: 10, 'abc': 30, 'abc': 50}
print(dict3)                # {10: 23, 1.23: 10, 'abc': 50}

3、字典的基本操作-查

1、查 - 获取字典的值

1、查单个(一次获取一个值)

"""
语法1:
    字典[键]   -   获取字典中指定键对应的值
    获取一个不存在的键时会报错
"""

cat = {'name': '板栗', 'age': 2, 'breed': '金渐层', 'color': '金'}
print(cat['name'])              # 板栗
print(cat['breed'])             # 金渐层

"""
语法2:
a.字典.get(键)   -   获取字典中指定键对应的值
    获取一个不存在的键时不会报错,获取到的结果时None
b.字典.get(键,默认值)
    获取一个不存在的键时不会报错,返回默认值
"""
print(cat.get('age'))           # 2
print(cat.get('color'))         # 金


# print(cat['weight'])          # 键不存在会报错,获取一个不存在的键时会报错
print(cat.get('weight'))        # None,获取一个不存在的键时不会报错,获取到的结果时None
print(cat.get('weight', 5))     # 获取一个不存在的键时不会报错,返回默认值

2、遍历

"""
1)
for 键 in 字典:
    pass

2)
for 键,值 in 字典.item():
    print(键,值)
"""

cat = {'name': '板栗', 'age': 2, 'breed': '金渐层', 'color': '金'}
for x in cat:
    print(x, cat[x])
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': 100, '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.get('name'))

# 2.获取讲师的名字

print(class1.get('lecturer').get('name'))

# 3.获取班主任电话号码

print(class1.get('class_teacher').get('tel'))

# 4、统计学生中男生的数量

all_students = class1.get('students')
count = 0
for x in all_students:
    if x.get('gender') == '男':
        count += 1
print('男生的数量:', count)

# 5、计算所有学生分数的平均分
# 方法1:

all_students = class1.get('students')
sum1 = 0
for x in all_students:
    sum1 += x.get('score')
print('平均分:', sum1/len(all_students))

# 方法2:

all_students = class1.get('students')
result = sum([stu['score'] for stu in all_students])/len(all_students)
print('平均分:', result)

# 6、获取分数最高的学生的名字
# 方法1:

all_students = class1.get('students')
max_score = max(stu['score'] for stu in all_students)
print(max_score)
names = [stu['name']for stu in all_students if stu['score'] == max_score]
print(names)

# 方法2:

# 假设第一个学生分数最高
all_students = class1.get('students')
max_score = all_students[0]['score']
names = [all_students[0]['name']]
for stu in all_students[1:]:
    score = stu['score']
    if score > max_score:
        max_score = score
        names.clear()
        names.append(stu['name'])
    elif score == max_score:
        names.append(stu['name'])
print(max_score, names)

# 7、获取所有紧急联系人的电话

for stu in all_students:
    print(stu['linkman']['tel'])

4、字典增删改

1、增/改 - 添加键值对

1、字典[键] = 值 - 如果键存在就修改指定键对应的值,如果键不存在就添加键值对

# 修改
cat1 = {'name': '小金', 'breed': '金渐层', 'weight': '5'}
cat1['name'] = '板栗'
print(cat1)
# {'name': '板栗', 'breed': '金渐层', 'weight': '5'}

# 添加
cat1['age'] = 2
print(cat1)
# {'name': '板栗', 'breed': '金渐层', 'weight': '5', 'age': 2}

2、字典. setdefault (键, 值) - 添加键值对,如果键不存在就添加键值对,如果键存在就不动字典

cat1.setdefault('color', '白')
print(cat1)

# {'name': '板栗', 'breed': '金渐层', 'weight': '5', 'age': 2, 'color': '白'}

cat1.setdefault('weight', '5')
print(cat1)

# {'name': '板栗', 'breed': '金渐层', 'weight': '5', 'age': 2, 'color': '白'}
2、删 - 删除键值对
"""
del 字典[键]   -  删除指定键对应的键值对
字典.pop(键)   -   取出指定键对应的值 
"""
cat2 = {'name': '小金', 'breed': '金渐层', 'color': '金', 'age': 2, 'weight': '5'}
del cat2['color']
print(cat2)
# {'name': '小金', 'breed': '金渐层', 'age': 2, 'weight': '5'}

result = cat2.pop('age')
print(cat2, result)
# {'name': '小金', 'breed': '金渐层', 'weight': '5'} 2

5、字典相关操作函数和方法

1、相关操作

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
2、相关函数:len、dict
"""
a.len(字典)   -  获取字典中键值对的个数

b.dict(数据)  -   将指定数据转换成字典
对数据的要求: 1.数据本身是一个序列
            2.序列中的元素必须都是有且只有两个元素的小序列,并且其中第一个元素是不可变的数据
"""
print(len(dict1))           # 3
seq = ['ab', 'cd', 'ef']
print(dict(seq))            # {'a': 'b', 'c': 'd', 'e': 'f'}

seq = [(10, 20), range(2), 'he']
print(dict(seq))            # {10: 20, 0: 1, 'h': 'e'}
3、相关方法

1、字典.clear() - 清楚字典

2、字典.copy() - 复制字典

3、
字典.keys() - 返回一个序列,序列中的元素是字典所有的键
字典.values() - 返回一个序列,序列中的元素是字典所有的值
字典.items() - 返回一个序列,序列中的元素是每一对键和值组成的元素

cat2 = {'name': '小金', 'breed': '金渐层', 'color': '金', 'age': 2, 'weight': '5'}

print(cat2.keys())      
# dict_keys(['name', 'breed', 'color', 'age', 'weight'])

print(cat2.values())    
# dict_values(['小金', '金渐层', '金', 2, '5'])

print(cat2.items())     
# dict_items([('name', '小金'), ('breed', '金渐层'), ('color', '金'), ('age', 2), ('weight', '5')])

4、update

1)字典.update(序列) - 将序列中的元素全部添加到字典中,序列必须是可以转换成字典的序列

2)字典1.update(字典2) - 将字典2中所有的键值对都添加到字典1里面

dict2 = {'a': 1, 'b': 2}
dict3 = {'c': 12, 'd': 34, 'a': '1000'}
dict2.update(dict3)
print(dict2)            # {'a': '1000', 'b': 2, 'c': 12, 'd': 34}

6、字典推导式

1、{表达式1(键):表达式2(值) for 变量 in 序列}
result = {x: x*2 for x in range(5)}
print(result)           # {0: 0, 1: 2, 2: 4, 3: 6, 4: 8}
2、{表达式1(键):表达式2(值) for 变量 in 序列 if 条件语句}
result = {x: x for x in range(10) if x % 3}
print(result)           # {1: 1, 2: 2, 4: 4, 5: 5, 7: 7, 8: 8}

作业

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

    stu = {'name': '朴彩英', 'age': 25, 'single subject': 99, 'tel': 15681188570, 'gender': '女'}
    print(stu)
    
  2. 定义一个列表,在列表中保存6个学生的信息(学生信息中包括: 姓名、年龄、成绩(单科)、电话、性别(男、女、不明) )

    students = [{'name': '张良', 'age': 16, 'single subject': 99, 'tel': 123, 'gender': '男'},
                {'name': '甄姬', 'age': 25, 'single subject': 55, 'tel': 234, 'gender': '不明'},
                {'name': '貂蝉', 'age': 22, 'single subject': 100, 'tel': 345, 'gender': '女'},
                {'name': '王昭君', 'age': 20, 'single subject': 95, 'tel': 456, 'gender': '女'},
                {'name': '李白', 'age': 15, 'single subject': 23, 'tel': 567, 'gender': '男'},
                {'name': '诸葛亮', 'age': 23, 'single subject': 96, 'tel': 678, 'gender': '不明'}
    ]
    
    1. 统计不及格学生的个数

      count = 0
      for stu in students:
          if stu.get('single subject') < 60:
              count += 1
      print(count)			# 2
      
    2. 打印不及格未成年学生的名字和对应的成绩

      for stu in students:
          if stu.get('single subject') < 60:
               if stu.get('age') < 18:
                   print(stu['name'], stu['single subject'])		# 李白 23
      
    3. 求所有男生的平均年龄

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

      for stu in students:
          if stu['tel'] % 10 == 8:
              print(stu['name'])				# 诸葛亮
      
    5. 打印最高分和对应的学生的名字

      max_score = students[0]['single subject']
      names = [students[0]['name']]
      for stu in students[1:]:
          score = stu['single subject']
          if score > max_score:
              max_score = score
              names.clear()
              names.append(stu['name'])
          elif score == max_score:
              names.append(stu['name'])
      print(max_score, names)                     # 100 ['貂蝉']
      
    6. 删除性别不明的所有学生

      result = []
      for stu in students:
          if stu['gender'] == '不明':
              result.append(stu['name'])
              del stu
      print(result)					# ['甄姬', '诸葛亮']
      
    7. 将列表按学生成绩从大到小排序(挣扎一下,不行就放弃)

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

    class1 ={
        'class_name': 'python2201',
        'address': '十二教室',
        'class_teacher': {
            'name': '张瑞燕',
            'age': 25,
            'gender': '女',
            'tel': 1234567
        },
        'lecturer': {
            'name': '余婷',
            'age': 20,
            'gender': '女',
            'tel': 2345678
        },
        'students': [
            {'name': '小乔', 'age': 15, 'gender': '女', 'height': 160, 'tel': 123, 'linkman': {'name': '周瑜', 'tel': 1234}},
            {'name': '甄姬', 'age': 17, 'gender': '女', 'height': 157, 'tel': 234, 'linkman': {'name': '曹操', 'tel': 2345}},
            {'name': '孙策', 'age': 23, 'gender': '男', 'height': 180, 'tel': 345, 'linkman': {'name': '大乔', 'tel': 3456}},
            {'name': '韩信', 'age': 24, 'gender': '男', 'height': 184, 'tel': 456, 'linkman': {'name': '李白', 'tel': 4567}},
            {'name': '貂蝉', 'age': 15, 'gender': '女', 'height': 163, 'tel': 567, 'linkman': {'name': '赵云', 'tel': 5678}},
            {'name': '西施', 'age': 16, 'gender': '女', 'height': 159, 'tel': 678, 'linkman': {'name': '曜仔', 'tel': 6789}}
        ]
    }
    
  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. 利用列表推导式获取所有狗的品种

      [‘银狐’, ‘法斗’, ‘土狗’, ‘哈士奇’, ‘银狐’, ‘土狗’]

      result = [x['breed']  for x in dogs]
      print(result)			
      
      # ['银狐', '法斗', '土狗', '哈士奇', '银狐', '土狗']
      
    2. 利用列表推导式获取所有白色狗的名字

      [‘贝贝’, ‘可乐’]

      result = [ x['color']  for x in dogs if x['color'] == '白色']
      print(result)
      
      # ['贝贝', '可乐']
      
    3. 给dogs中没有性别的狗添加性别为 ‘公’

      for x in dogs:
          x.setdefault('gender', '公')
      print(dogs
      
      """
      
      [{'name': '贝贝', 'color': '白色', 'breed': '银狐', 'age': 3, 'gender': '母'}, {'name': '花花', 'color': '灰色', 'breed': '法斗', 'age': 2, 'gender': '公'}, {'name': '财财', 'color': '黑色', 'breed': '土狗', 'age': 5, 'gender': '公'}, {'name': '包子', 'color': '黄色', 'breed': '哈士奇', 'age': 1, 'gender': '公'}, {'name': '可乐', 'color': '白色', 'breed': '银狐', 'age': 2, 'gender': '公'}, {'name': '旺财', 'color': '黄色', 'breed': '土狗', 'age': 2, 'gender': '母'}]
      
      """
      
    4. 统计 ‘银狐’ 的数量

      count = 0
      for x in dogs:
          if x['breed'] == '银狐':
              count += 1
      print(count)				# 2
      
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值