字典的增删改查
Posted 虫洞小鳗鱼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字典的增删改查相关的知识,希望对你有一定的参考价值。
字典:python中非常重要的数据类型,在python中唯一一个映射的数据类型
数据类型分类
按照数据可变与不可变:
# 不可变数据类型: int str bool tuple
# 可变数据类型: list,dict,set
1 键值对
#字典的 key:value# key 是唯一的 且是不可变数据类型 int,str bool tuple
#value:任意数据类型
2 . 增加数据
dic = {"name":"jin","age":18,"sex":"male"} #增 dic[\'key\'] = value # 有key 就覆盖,没有key就添加. # dic[\'name2\'] = \'依米\' #没有key name2 就会添加新数据 # print(dic) # dic[\'name\'] = \'王子\' #有key name 那么name的值就会被替代 # print(dic)
结果:
.setdefault 方法有key不变, 没有key才添加.
dic = {"name":"jin","age":18,"sex":"male"} #有key不变,没有key才添加. # dic.setdefault(\'hobby\') #没有会添加 # print(dic) # dic.setdefault(\'hobby\',\'开船\')#有就不会变 # print(dic) # dic.setdefault(\'name\',\'太白\')#有就不会变 # print(dic)
结果:
3. 删
.pop 按key删除,有返回值,并且如果没有此key,可设置返回值
dic = {"name":"jin","age":18,"sex":"male"} ret = dic.pop(\'sex\') print(ret) ret = dic.pop(\'sex1\',\'没有此键\') print(ret)
结果:
清空和删除 clear是清空数据 字典还存在 del是删除字典
dic = {"name":"jin","age":18,"sex":"male"} dic.clear() print(dic) # del 删除字典,删除键值对 del dic print(dic)
结果:
.popitem()随机删除一个数据,并产生返回值. 但是python3.6版本以后默认删除最后一个数据
dic = {"name":"jin","age":18,"sex":"male"} #popitem() 随机删除 ret = dic.popitem() print(ret) print(dic)
结果:
4. 改
dic = {"name":"jin","age":18,"sex":"male"} # 改 #dic[\'key\'] = value # 有key 就覆盖. dic["name"]=(1)
结果:
update 将dic的键值对,覆盖,添加到dic2 中,dic不变
dic = {"name":"jin","age":18,"sex":"male"} dic2 = {"name":"alex","weight":75} dic2.update(dic) print(dic) print(dic2)
结果:
5 查
.get方法通过key找值,如果没有可以加值告知 不添加默认为none
dic = {"name":"jin","age":18,"sex":"male"} # 查 print(dic[\'name\']) #输入key 找对应value print(dic.get(\'name\')) print(dic.get(\'name2\',\'没有此键值对\')) print(dic)
结果:
a,b能同时赋值,只要后面有两个元素, int list dict tuple等类型都行
a = 1 #一行代码实现a,b值互换
b = 3 a,b = b,a print(a,b) a,b = [\'alex\',\'wusir\'] print(a,b) a,b = (\'alex\',\'wusir\') print(a,b)
结果:
6 找出所有key
dic = {"name":"jin","age":18,"sex":"male"} for k in dic: print(k) for k in dic.keys(): print(k)
7 找出所有values
dic = {"name":"jin","age":18,"sex":"male"} for v in dic.values(): print(v)
结果:
8 找出所有键值对;
dic = {"name":"jin","age":18,"sex":"male"} for k,v in dic.items(): print(k,v) for k in dic: print(k,dic[k])
结果:
9 字典的嵌套
dic = {
\'name\':\'金鑫\',
\'name_list\':[1,2,3,\'李杰\'],
1:{
\'python10\':[\'小黑\',\'萌哥\'],
\'老男孩\':{\'name\':\'oldboy\',\'age\':56}
}
}
#1,[1,2,3,\'李杰\']追加\'wusir\'
#2, [\'小黑\',\'萌哥\'] 小黑 萌哥中间 插入一个花哥
#3, {\'name\':\'oldboy\',\'age\':56} 添加一个键值对,hobby:男人
dic[\'name_list\'].append(\'wusir\') print(dic) l = dic[1][\'python10\'] l.insert(1,\'花哥\') print(dic) dic1 = dic[1] dic2 = dic1[\'老男孩\'] dic2[\'hobby\'] = \'男人\'
结果:
以上是关于字典的增删改查的主要内容,如果未能解决你的问题,请参考以下文章