Python语法---字典

本文介绍了Python中字典的创建、元素获取、删除与修改、键值判断、遍历以及字典生成式的基本用法,涵盖了字典操作的关键点。
摘要由CSDN通过智能技术生成

一、字典的创建

scores={'张三':100,'李四':98,'王五':45}
print(scores)
print(type(scores))
'''第二种创建dict()'''
student=dict(name='jack',age=20)
print(student)
d={}
print(d)

二、获取字典的元素

'''获取字典的元素'''
scores={'张三':100,'李四':98,'王五':45}
'''第一种方式,使用[]'''
print(scores['张三'])
print(scores.get('张三'))
print(scores.get('陈六')) #None
print(scores.get('麻七',99)) #99是在查找'麻七'所对的value不存在时,提供的一个默认值

删除、判断、修改key

'''key的判断'''
scores={'张三':100,'李四':98,'王五':45}
print('张三' in scores)
print('张三' not in scores)
del scores['张三']  #删除指定的key-value对
#scores.clear()  #清空字典的元素
print(scores)
scores['陈六']=98   #新增元素
print(scores)
scores['陈六']=100  #修改元素
print(scores)

获得所有的key-value

scores={'张三':100,'李四':98,'王五':45}
#获取所有的key
keys=scores.keys()
print(keys)
print(type(keys))
print(list(keys))  #将所有的key组成的视图转成列表
#获取所有的value
values=scores.values()
print(values)
print(type(values))
print(list(values))
#获取所有的key-value对
items=scores.items()
print(items)
print(list(items))  #转换之后的列表元素是由元组组成 (元组将在下个章节讲解)

遍历所有的字典元素

scores={'张三':100,'李四':98,'王五':45}
#字典元素的遍历
for  item  in scores:
    print(item,scores[item],scores.get(item))

字典生成式

items=['Fruits','Books','Others']
prices=[96,78,85,100,120]
print(items[0])
d={(item.upper(),price)    for item ,price in zip(items,prices)  }
print(d)
# Fruits
# {('BOOKS', 78), ('FRUITS', 96), ('OTHERS', 85)}
  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值