2-11字典类型的详细方法
Posted echo-kid-coding
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2-11字典类型的详细方法相关的知识,希望对你有一定的参考价值。
字典类型的详细方法
>>> #查找 ... >>> 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字典类型的详细方法的主要内容,如果未能解决你的问题,请参考以下文章