码迷,mamicode.com
首页 > 其他好文 > 详细

dict的增,删,改,查

时间:2017-10-29 14:32:57      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:col   返回值   item   items   相同   键值   元祖   key   update   

 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的增,删,改,查

标签:col   返回值   item   items   相同   键值   元祖   key   update   

原文地址:http://www.cnblogs.com/j6852/p/7749945.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!