第八天 字典

第八天 字典

用变量获取元素

1. 使用多个变量同时获取列表或者元组的元素
# 要求变量的个数必须和元组/列表元素的个数保持一致
t1 = (10, 20, 30, 40)
a, b, c, d = t1
print(a, b, c, d)

point = (10, 89)
x, y = point

# 2.使用多个变量同时获取列表或者元组的元素
# 当变量的个数小于元素的个数的时候,必须在某一个变量前加*
# 获取的时候先让不带*的变量按照顺序获取对应的数据,把剩下的全部保存到带*的变量中。
list1 = [10, 20, 30, 40, 50, 60]
x, y, *z = list1
print(x, y, z)      # 10 20 [30, 40, 50, 60]

x, *y, z = list1
print(x, z, y)      # 10 60 [20, 30, 40, 50]

*x, y, z = list1
print(y, z, x)      # 50 60 [10, 20, 30, 40]

x, *y, z, t = list1
print(y)        # [20, 30, 40]


student = ('小明', 18, '男', 89, 78, 99)
name, age, gender, *scores = student
print(name, age, gender, scores)

# 3. 元组在没有歧义的情况下,()可以省略
t1 = (10, 20, 30)
print(t1)

t2 = 10, 20, 30
print(t2, type(t2))     # (10, 20, 30) <class 'tuple'>

认识字典

# 定义一个变量保存一个学生的信息
# 使用列表
student = ['老王', '小花', '男', 67, 89, 78, 34]
print(student[0])

# 使用字典
student = {'name': '小明', 'gender': '男', '年龄': 67, 'chinese': 89, '数学成绩': 78, 'english': 34}
print(student['name'])

# 当需要保存多个意义不同的数据的时候,就使用字典

# 1.什么是字典(dict)
"""
1)字典是容器型数据类型(序列); 将{}作为容器的标志,里面多个键值对用逗号隔开(一个键值对就是一个元素):{键1:值1, 键2:值2,...}
2)字典是可变的(支持增删改);字典无序(不支持下标操作)
3)元素的要求 - 元素是键值对
键的要求:只有不可变类型的数据可以作为键,一般使用字符串(做到见名知义);键唯一
值的要求:没有要求
"""
# 空字典
d1 = {}
print(d1, type(d1))     # {} <class 'dict'>

# 字典无序
print({'a': 10, 'b': 20} == {'b': 20, 'a': 10})     # True

# 键必须是不可变的数据
d2 = {'a': 10, 10: 20, (1, 2): 30}
print(d2)       # {'a': 10, 10: 20, (1, 2): 30}

# d3 = {'a': 10, 10: 20, [1, 2]: 30}        # 报错!键不能是可变类型的列表

# 键是唯一的
d4 = {'a': 10, 'b': 20, 'c': 30, 'a': 100}
print(d4)       # {'a': 100, 'b': 20, 'c': 30}

字典的增删改查

# 1. 查  -  获取值
# 1)查单个
"""
字典[键]  - 获取指定键对应的值,键不存报错!

字典.get(键)  - 获取指定键对应的值,键不存在返回None
字典.get(键, 默认值)  -   获取指定键对应的值,键不存在返回指定默认值
"""
stu = {'name': '小明', 'age': 20, 'gender': '男', 'tel': '110'}
print(stu['name'])
print(stu['tel'])
# print(stu['score'])     # 报错:KeyError: 'score'

print(stu.get('name'))
print(stu.get('tel'))
print(stu.get('score'))     # None
print(stu.get('score', 0))


students = [
    {'name': 'stu1', 'age': 34, 'gender': '男', 'tel': '110', 'score': 89},
    {'name': 'stu2', 'age': 20, 'gender': '女', 'tel': '110', 'score': 70},
    {'name': 'stu3', 'age': 19, 'gender': '男', 'tel': '110'},
    {'name': 'stu4', 'age': 22, 'gender': '男', 'tel': '110', 'score': 25}
]
count = 0
sum1 = 0
for x in students:
    # 确定键一定存在用[]语法获取
    if x['gender'] == '女':
        count += 1
    # 键可能存在可能不存在使用get方法获取
    sum1 += x.get('score', 0)
print('女生人数:', count, '总分:', sum1)


# 2)遍历(了解)
"""
for 键 in 字典:
    pass
"""
stu = {'name': '小明', 'age': 20, 'gender': '男', 'tel': '110'}
for x in stu:
    print('x:', x, stu[x])


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

字典.setdefault(键, 值)  - 添加键值对(只添加不修改)
"""
stu = {'name': '小明', 'age': 20, 'gender': '男', 'tel': '110'}

# 键存在就修改
stu['name'] = '小花'
print(stu)      # {'name': '小花', 'age': 20, 'gender': '男', 'tel': '110'}

# 键不存在就添加
stu['score'] = 100
print(stu)      # {'name': '小花', 'age': 20, 'gender': '男', 'tel': '110', 'score': 100}

stu.setdefault('age', 30)
print(stu)      # {'name': '小花', 'age': 20, 'gender': '男', 'tel': '110', 'score': 100}

stu.setdefault('height', 180)
print(stu)      # {'name': '小花', 'age': 20, 'gender': '男', 'tel': '110', 'score': 100, 'height': 180}


orders = [
    {'goods_name': '泡面', 'price': 3.5, 'discount': 0.9, 'count': 3},
    {'goods_name': '矿泉水', 'price': 1, 'count': 5},
    {'goods_name': '火腿肠', 'price': 2.5, 'count': 2},
    {'goods_name': '卤蛋', 'price': 2, 'count': 4, 'discount': 0.85}
]

for x in orders:
    x.setdefault('discount', 1)

print(orders)

# 3. 删  - 删除键值对
"""
1) del 字典[键]    -   删除指定键对应的键值对
2) 字典.pop(键)    -   取出指定键对应的值
"""
stu = {'name': '小明', 'age': 20, 'gender': '男', 'tel': '110'}

del stu['gender']
print(stu)          # {'name': '小明', 'age': 20, 'tel': '110'}

result = stu.pop('tel')
print(stu, result)          # {'name': '小明', 'age': 20} 110

字典和列表在实际开发中的应用

# 定义一个变量保存一个班级信息
class1 = {
    'name': 'Python2107',
    'address': '18教',
    'lecturer': [
        {'name': '余婷', 'qq': '726550822', 'age': 18},
        {'name': '骆昊', 'qq': '67273', 'age': 38}
    ],
    'students': [
        {'name': 'stu1', 'tel': '101922', 'gender': '男', 'age': 20, 'linkman': {'name': '张三', 'tel': '120'}},
        {'name': 'stu2', 'tel': '1012911', 'gender': '女', 'age': 19, 'linkman': {'name': '李四', 'tel': '119'}},
        {'name': 'stu3', 'tel': '0192342', 'gender': '女', 'age': 30, 'linkman': {'name': 'Bob', 'tel': '100'}},
        {'name': 'stu4', 'tel': '1101823', 'gender': '男', 'age': 29, 'linkman': {'name': '王五', 'tel': '110'}},
        {'name': 'stu5', 'tel': '102323', 'gender': '男', 'age': 23, 'linkman': {'name': '老王', 'tel': '1203'}},
        {'name': 'stu6', 'tel': '192389123', 'gender': '女', 'age': 20, 'linkman': {'name': '小明', 'tel': '130'}},
        {'name': 'stu7', 'tel': '099121234', 'gender': '男', 'age': 25, 'linkman': {'name': '小花', 'tel': '11923'}}
    ]
}

# 练习:
# 1) 班级名称
print('1)班级名称:', class1['name'])

# 2)获取第一个讲师的姓名
print('2)第一个讲师的姓名:', class1['lecturer'][0]['name'])

# 3)获取所有讲师的qq
print('3)所有的讲师的qq:')
for x in class1['lecturer']:
    print(x['qq'])

# 4)获取所有学生的姓名
print('4)所有学生的姓名:')
for x in class1['students']:
    print(x['name'])

# 5)统计学生女生的个数
print('5)学生女生的个数:')
count = 0
for x in class1['students']:
    if x['gender'] == '女':
        count += 1
print(count)

# 6)获取所有尾号是0的联系人的姓名
print('6)尾号是0的联系人的姓名:')
for x in class1['students']:
    linkman = x['linkman']

    if int(linkman['tel']) % 10 == 0:
        print(linkman['name'])

    # if linkman['tel'][-1] == '0':
    #     print(linkman['name'])

字典相关操作函数和方法

# 1. 运算符
# 相对列表,字典不支持: +、*、比较大小

# 2.相关函数
"""
dict(数据)  - 将数据转换成字典
数据的要求:
1) 这个数据必须是一个序列
2) 序列中元素必须是有且只有两个元素的小序列, 两个元素中第一个元素是不可变的数据
"""
x = ['ab', range(2), (10, 20)]
result = dict(x)
print(result)       # {'a': 'b', 0: 1, 10: 20}

# 3. 相关方法
# 1) 字典.clear()  - 清空字典
# 2) 字典.copy()  - 赋值字典产生一个一模一样的新字典(地址不同)
# 3)
"""
字典.values()     -       获取字典所有的值,返回一个新的序列
字典.keys()       -       获取字典所有的键,返回一个新的序列
字典.items()      -       获取所有的键和值,每一个键值对对应一个元组,返回一个新的序列
"""
dog = {'name': '旺财', 'age': 2, 'color': '黄色', 'breed': '土狗'}

print(dog.values())     # dict_values(['旺财', 2, '黄色', '土狗'])
print(dog.keys())       # dict_keys(['name', 'age', 'color', 'breed'])
print(dog.items())      # dict_items([('name', '旺财'), ('age', 2), ('color', '黄色'), ('breed', '土狗')])

list1 = [19, 23, 89, 192, 89]
for x in list1:
    print('x:', x)

list1 = [(10, 20), (200, 300), (11, 22)]
for x in list1:
    print('x:', x)

for x, y in list1:
    print('x:', x, 'y:', y)

for key, value in dog.items():
    print(key, value)

# 练习:使用列表推导式交换字典的键和值
dict1 = {10: 20, 'a': 'b', 'c': 30}
# {20: 10, 'b': 'a', 30: 'c'}
# dict([(20, 10), ('b', 'a'), (30, 'c')])
result = dict([(value, key) for key, value in dict1.items()])
print(result)       # {20: 10, 'b': 'a', 30: 'c'}

result = {value: key for key, value in dict1.items()}
print(result)       # {20: 10, 'b': 'a', 30: 'c'}

# 字典推导
"""
{表达式1:表达式2 for 变量 in 序列}
{表达式1:表达式2 for 变量 in 序列 if 条件语句}
"""
result = {x: x*2 for x in range(5)}
print(result)       # {0:0, 1:2, 2:4, 3:6, 4:8}

result = {x: x*2 for x in range(5) if x % 2}
print(result)    # {1:2, 3:6}

# 4) 字典1.update(字典2)  - 将字典2中所有的键值对都添加到字典1
d1 = {'a': 10, 'b': 20, 'c': 11}
d2 = {'c': 30, 'd': 40}
d1.update(d2)
print(d1)       # {'a': 10, 'b': 20, 'c': 30, 'd': 40}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值