day8.字典

字典

用变量获取元素

  • 使用多个变量同时获取列表或者元组的元素
t1 = (10, 20, 30, 40)
a, b, c, d = t1
print(a, b, c, d)
  • 使用多个变量同时获取列表或者元组的元素
  • 当变量的个数小于元素的个数的时候,必须在某一个变量前加*

    获取的时候先让不带的变量按照顺序获取对应的数据,把剩下的全部保存到带的变量中

student = ('朱武兵', '18', '男', 90, 34, 56, 67, 12, 89)
name, age, gender, *scores = student
print(name)
print(age)
print(gender)
print(scores)
  • 元组在没有歧义的情况下,()可以省略
t1 = (10, 20, 30)
print(t1)
t2 = 20, 30, 40
print(t2, type(t2))

字典

  • 字典是容器型数据类型(序列);将{}作为容器的标志里面多个键值对用逗号隔开(一个键值对就是一个元素)

  • 字典是可变的(支持增删改查操作);字典无序(不支持下标操作)

  • 元素的要求 - 元素就是键值对

  • 键的要求:只有不可变类型的数据可以作为键,一般使用字符串;键唯一只能出现一次

  • 值的要求:没有要求

d1 = {}
print(d1, type(d1))#空字典
print({'a': 10, 'b': 20} == {'b': 20, 'a': 10})#字典无序
d2 = {'a': 10, 10: 20, (10, 20): 30}
print(d2)
d3 = {'a': 10, 10: 20, [10, 20]: 30}
print(d3)	
d4 = {'a': 10, 10: 20, 'c': 30}
print(d4)  #键必须是不可变的数据,键唯一

字典的增删改查

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

print(stu.get('name'))
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)
  • 遍历
forin 字典:
pass
stu = {'name': '小明', 'age': 20, 'gender':'男', 'tel':'110'}
for i in stu:
    print('i:', i, stu[i])
  • 增、改:
stu = {'name': 'stu1', 'age': 19, 'gender': '男', 'tel': '120'}
# 键存在就修改  
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)
  • 删 - 删除键值对
stu = {'name': '小明', 'age': 20, 'gender': '男', 'tel': '110'}
del stu['gender']
print(stu) # {'name': '小明', 'age': 20, 'tel': '110'}

result = stu.pop('tel')
print(stu, result)	

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

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(class['name'])
# 2)获取第一个讲师的姓名
print(class['lecturer'][0]['name'])
# 3)获取所有讲师的qq
for i in class['lecturer']:
    print(i['qq'])
# 4)获取所有学生的姓名
for i in class['students']
print(i.get('name'))
# 5)统计学生女生的个数
nums = 0
for i in class['students']:
    if i['gender'] == '女':
        nums += 1
print(numms)
# 6)获取所有尾号是0的联系人的姓名
for i in class['students']:
    linkman = i['linkman']
    if linkman['tel'][-1] == '0':
        print(linkman['name'])

字典相关操作函数和方法

  • 运算符:相对列表,字典不支持:+、*、比较大小.
  • 相关函数:dict(数据) - 将数据转换成字典,数据必须是一个序列,序列中元素必须是有且只有两个元素的小序列,两个元素中第一个元素是不可变的数据
  • 相关方法:字典.clear() - 清空字典字典,copy() - 赋值字典产生一个一模一样的薪字典(地址不同),字典.values() - 获取字典所有的值,返回一个新的序列字典.keys() - 获取字典所有的键,返回一个新的列表,字典.items() - 获取所有的键和值,每一个键值对对应一个元组,返回一个新的序列
dog = {'name': '旺财', 'age': 2, 'color': '黄色', 'breed': '土狗'}
print(dog.value())		# 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)
  • 字典推导
{表达式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.update(字典2) - 将字典2中所有的键值对都添加到字典1
d1 = {'a': 10, 'b': 20, 'c': 11}
d2 = {'c': 30, 'd': 40}
d1.update(d2)
print(d1) 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值