dict的增,删,改,查

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了dict的增,删,改,查相关的知识,希望对你有一定的参考价值。

 dict是无序的 ,数据关联性强,键值对,唯一一个个映射的数据类型
  字典的键必须是可哈希的数据类型 (字符串,数字,bool,元祖)并且是唯一的.
  不可哈希的:(列表,字典)

dict的增

1:直接加键值对,如果和要增的相同就会覆盖,没有才添加

dic = {name:wujiang,age:18,}
dic[hobby] = it
print(dic)   #:{‘name‘: ‘wujiang‘, ‘age‘: 18, ‘hobby‘: ‘it‘} 

2.setdefault()有的键值对不变,没有的添加

dic = {name:wujiang,age:18,}
dic.setdefault(k1,v)
print(dic)   #{‘name‘: ‘wujiang‘, ‘age‘: 18, ‘k1‘: ‘v‘}

dict的删

1.pop按照键去删,有返回值

dic = {name:wujiang,age:18,}
dic.pop(name)
print(dic)  #:{‘age‘: 18}

2.del 直接删键

dic = {name:wujiang,age:18,}
del dic[age]  #注意格式
print(dic) #:{‘name‘: ‘wujiang‘}

3.clear 清空列表

dic = {name:wujiang,age:18,}
dic.clear()
print(dic)  #{}

dict的改:

1.直接改键

dic = {name:wujiang,age:18,}
dic[name] = taibai
print(dic)  #:{‘name‘: ‘taibai‘, ‘age‘: 18}

2.update 更新原dic(就是添加并覆盖)

dic = {name:wujiang,age:18,hobby:lol}
dic.update( {name:taibai})
print(dic)     #:{‘name‘: ‘taibai‘, ‘age‘: 18, ‘hobby‘: ‘lol‘}
                  # :只变原字典        

dict的查

1.直接查键

dic = {name:wujiang,age:18,hobby:lol}
dic1 = dic[hobby]
print(dic1)    #:lol

2.get  查键,没有返回None

dic = {name:wujiang,age:18,hobby:lol}
dic1 = (dic.get(jop))
print(dic1)   #:None

dic的特殊类型:keys(键),values(值),items(键值对),

dic = {name:wujiang,age:18,hobby:lol}
dic1 = dic.keys()
print(dic1)  #:dict_keys([‘name‘, ‘age‘, ‘hobby‘])
dic = {name:wujiang,age:18,hobby:lol}
dic1 = dic.values()
print(dic1) #:dict_values([‘wujiang‘, 18, ‘lol‘])
dic = {name:wujiang,age:18,hobby:lol}
dic1 = dic.items()
print(dic1)
 #:dict_items([(‘name‘, ‘wujiang‘), (‘age‘, 18), (‘hobby‘, ‘lol‘)])

 

以上是关于dict的增,删,改,查的主要内容,如果未能解决你的问题,请参考以下文章

1-24.list的增,删,改,查

数据库的增,删,查,改

网站的增 / 删 / 改 / 查 时常用的 sql 语句

用springboot框架做一个web项目实现简单的增,删,改,查功能的流程

MySQL的基本操作 库和表的增删改查命令

求ACCESS数据库的增删改语句