python字典

本文详细介绍了Python字典的基本操作,包括创建、新增、删除和修改元素,以及通过key、get()、keys()、values()和items()进行查找。此外,还展示了字典的循环遍历方式,包括遍历key、value以及键值对。通过实例演示了字典的各种常用方法,帮助理解字典在数据存储和检索中的应用。
摘要由CSDN通过智能技术生成

1、字典的应用场景

字典里面以键值对的形式出现,字典数据和数据顺序没有关系。后期无论数据如何变化,只需要按照对应的键的名字查找数据即可。

2、创建字段的语法

2.1、特点:

符号位大括号 数据为键值对出现 各个键值对之间用逗号隔开

dict ={'name':'tom','age':'20','gender':'男'}
print(dict)
dict1 ={}
print(dict1)

3、字典的常见操作

3.1、新增

dict ={'name':'tom','age':'20','gender':'男'}
dict['name']='lily'
print(dict)

3.2、删除

dict ={'name':'tom','age':'20','gender':'男'}
del(dict)
del dict['name']
dict.clear()

3.3、修改

dict ={'name':'tom','age':'20','gender':'男'}
dict['name']='lily'
print(dict)

3.4、查找

3.4.1、按照key查找
dict ={'name':'tom','age':'20','gender':'男'}
print(dict['name'])
3.4.2、get() 若不存在,返回none
dict ={'name':'tom','age':'20','gender':'男'}
print(dict.get('name'))
print(dict.get('names'))
3.4.3、keys() 查找所有keys
3.4.4、value() 查找所有value
dict ={'name':'tom','age':'20','gender':'男'}
print(dict.keys())
print(dict.values())
3.4.5、items() 查找所有元组

4、字典的循环遍历

4.1、遍历字典key

dict ={'name':'tom','age':'20','gender':'男'}
for key in dict.keys():
    print(key)

4.2、遍历字段value

dict ={'name':'tom','age':'20','gender':'男'}for value in dict.values():    print(value)

4.3、遍历字段的元素–键值对

dict ={'name':'tom','age':'20','gender':'男'}for item in dict.items():    print(item)

4.4、遍历字段的键值对(拆包)

dict ={'name':'tom','age':'20','gender':'男'}for item in dict.items():    print(item)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值