python----字典的增删改查

字典数据的增加

1、dict1={'name':'tom','age':18,'gender':'男'}

dict1['id']='110'

print(dict1)   #{'name':'tom','age':18,'gender':'男','id':110}

2、dict1={'name':tom,'age':18,'gender':'男'}

dict1['name']='rose'

print(dict1)  #dict1={'name':'rose','age':18,'gender':'男'}

        注意:如果key存在则修改这个key对应的值,如果key不存在则新增此键值对

2、字典数据的删除

del 字典名/del(字典名)----删除整个字典

 dict1={'name':tom,'age':18,'gender':'男'}

del dict1

------------------------------------------------------

dict1={'name':tom,'age':18,'gender':'男'}

del  dict1['name']

print (dict1)      #{'age':18,'gender':'男'}   删除指定的键值对

字典序列号.clear()清空字典

dict1={'name':tom,'age':18,'gender':'男'}

dict1.clear()  #{}

3、字典数据的查找

dict1={'name':tom,'age':18,'gender':'男'}

print(dict1['name'])  #'tom'    如果当前的key存在则返回值,如果没有就报错

  get()函数:字典序列.get(key,默认值)

        注意:如果当前查找的key不存在则返回第二个参数(默认值),如果省略第二个参数,则返回none

dict1={'name':tom,'age':18,'gender':'男'}

print(dict1.get('name'))   #tom

print(dict1.get('id'))   #none

keys()函数:查找字典中所有的key,返回可迭代的对象

dict1={'name':tom,'age':18,'gender':'男'}

print(dict1.keys())  #dict_keys(['name','age','gender'])

values()函数:朝朝字典中所有的值,返回可迭代的对象

dict1={'name':tom,'age':18,'gender':'男'}

print(dict1.values())  #dict_vules(['tom',18,'男'])

items()函数:查找字典中所有的键值对,返回可迭代的对象,里面的数据是元组

dict1={'name':tom,'age':18,'gender':'男'}

print(dict1.vaules())    #dict_item([('name','tom'),('age',18),('gender','男')])

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值