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

2-11字典类型的详细方法

时间:2019-07-18 13:25:27      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:key   error:   返回   class   one   用法   back   mil   most   

字典类型的详细方法

 

>>> #查找
...
>>> info = {stu1101: TengLan Wu, stu1102: LongZe Luola, stu1103: Xiao
Ze Maliya,
...  stu1104: Alex}
>>> "stu1102" in info #标准用法
True
>>> info.get(stu1102) #获取
LongZe Luola
>>> info[stu1102] #同上,但是看下面
LongZe Luola
>>> info[stu1105] #如果一个key不存在,就报错,get不会,不存在只返回None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: stu1105

 

>>> #删除
...
>>> info = {龙婷:[24,设计部,UI,23333],shanshan:[22,PR,designer,14556
],Alex:[30,开发部,engineer,2114]}
>>> info.pop(shanshan) #pop删除后 返回删除的值
[22, PR, designer, 14556]
>>> info
{龙婷: [24, 设计部, UI, 23333], Alex: [30, 开发部, engineer, 2114]}
>>> info
{龙婷: [24, 设计部, UI, 23333], Alex: [30, 开发部, engineer, 2114],
1: 2, 2: 2, 3: 2}
>>> info.popitem() #随机删
(3, 2)
>>> info.popitem()
(2, 2)
>>> info.popitem()
(1, 2)
>>> info
{龙婷: [24, 设计部, UI, 23333], Alex: [30, 开发部, engineer, 2114],
!: aaa}
>>> del info[!]
>>> info
{龙婷: [24, 设计部, UI, 23333], Alex: [30, 开发部, engineer, 2114]}
>>>

查找:get() 、中括号

删除:pop()   popitem()  del

多级字典的嵌套

其他方法

>>> info
{Alex: [23, IT], rain: [24, HR], jack: 22}
>>> info.keys() # 所有的key
dict_keys([Alex, rain, jack])

>>> info.values() #所有的value
dict_values([[23, IT], [24, HR], 22])

>>> info.items() #把key和value 合成元祖,把字典转成一个大列表
dict_items([(Alex, [23, IT]), (rain, [24, HR]), (jack, 22)])

>>> info1={TT:[11,qq]}
>>> info.update(info1)    #把两个字典合成一个 ,类似列表中的extend()
>>> info
{Alex: [23, IT], rain: [24, HR], jack: 22, TT: [11, qq]}
>>>

 

>>> info={Alex: [23, IT], rain: [24, HR], jack: 22, TT: [11, qq]}
>>> dic2 ={1:2,2:3,jack:[22,Jack Ma,Alibaba]}
>>> info.update(dic2)
>>> info
{Alex: [23, IT], rain: [24, HR], jack: [22, Jack Ma, Alibaba], TT: [11, qq], 1: 2, 2: 3}
>>>#upadate 没有的就创建,有的就覆盖
>>> info
{Alex: [23, IT], rain: [24, HR], jack: [22, Jack Ma, Alibaba], TT: [11, qq], 1: 2, 2: 3}
>>> info.setdefault(2,new2)
3
>>> info
{Alex: [23, IT], rain: [24, HR], jack: [22, Jack Ma, Alibaba], TT: [11, qq], 1: 2, 2: 3}
>>> info.setdefault(test,new2)
new2
>>> info
{Alex: [23, IT], rain: [24, HR], jack: [22, Jack Ma, Alibaba], TT: [11, qq], 1: 2, 2: 3, test: new2}
>>> info.fromkeys([A,B,C],Alex)
{A: Alex, B: Alex, C: Alex}

字典的循环

>>> info.fromkeys([A,B,C],Alex)
{A: Alex, B: Alex, C: Alex}

 

2-11字典类型的详细方法

标签:key   error:   返回   class   one   用法   back   mil   most   

原文地址:https://www.cnblogs.com/echo-kid-coding/p/11200408.html

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