一.字典的基本方法
1.新建字典
1)、建立一个空的字典
>>> dict1={} >>> dict2=dict() >>> dict1,dict2 ({}, {})
>>> dict1={1:'a',2:'b',3:'c'} >>> dict1 {1: 'a', 2: 'b', 3: 'c'}
>>> dict1=dict([(1,'a'),(2,'b'),(3,'c')]) >>> dict1 {1: 'a', 2: 'b', 3: 'c'}
2、获取方法
1)、get(key) 从字典中获取一个key对应的value,返回value
>>> dict1={1:'a',2:'b',3:'c'} >>> dict1.get(1) 'a'
如果字典里面不存在,则返回一个 NoneType
>>> type(dict1.get(4)) <type 'NoneType'>
>>> dict1.get(4,'not found') 'not found'
2)、keys() 获取字典中所有的key值,返回一个列表
>>> dict1.keys() [1, 2, 3]
3)、values() 与keys()方法对应,返回的字典中的所有value的列表
>>> dict1.values() ['a', 'b', 'c']
4)、items() 返回一个 (key,value)对应的元组
>>> dict1.items() [(1, 'a'), (2, 'b'), (3, 'c')]
5)、iterkeys() , itervalues() , iteritems() 也是分别获取所有的key,value,(key,value)元祖,只是不在是返回列表,而是一个迭代器
>>> for key in dict1.iterkeys(): print key 1 2 3
3、设置字典值的方法
1)、直接的方法就是
>>> dict1[4]='d' >>> dict1 {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
但是,这个方法就是,如果我想添加的key值已经在字典中,那么就会覆盖掉原来的value值
>>> dict1[4]='e' >>> dict1 {1: 'a', 2: 'b', 3: 'c', 4: 'e'}
2)、setdefault(key,value) 这个方法的好处就是,如果插入的key不存在字典中,那么插入字典并返回该value,否则的存在于字典中的话,那么返回存在的value,不会覆盖掉
>>> dict1 {1: 'a', 2: 'b', 3: 'c', 4: 'e'} >>> dict1.setdefault(5,'f') 'f' >>> dict1.setdefault(5,'g') 'f' >>> dict1 {1: 'a', 2: 'b', 3: 'c', 4: 'e', 5: 'f'}
4、删除字典
1)pop(key) 删除指定key的一项,成功返回一个删除项的value, 如果不存在,会抛出异常,所以在用这个方法时候,都要用判断 key是否存在,或者catch这个异常
>>> def pop_key(d,key): try: d.pop(key) print "sucess" except: print "key is not in dict" >>> dict1 {1: 'a', 2: 'b'} >>> pop_key(dict1,3) key is not in dict
或者
>>> def sub_dict2(d,key): if d.has_key(key): d.pop(key) print "sucess" else:print "key is not in dict" >>> pop_key(dict1,3) key is not in dict
2) popitem() 和pop()类似,只是他是删除一个(key,value)的元组
利用上面的方法,可以得使用一些进阶的用法
A、我们通过2个列表来创建一个字典,第一个列表是所有的key,第二个列表是所有的value
>>> list1=[1,2,3] >>> list2=['a','b','c'] >>> dict1=dict(zip(list1,list2)) >>> dict1 {1: 'a', 2: 'b', 3: 'c'}
B、找出某一个字典的子字典
>>> dict1 {1: 'a', 2: 'b', 3: 'c'} >>> dict1=dict([(1,'a'),(2,'b'),(3,'c')]) >>> dict1 {1: 'a', 2: 'b', 3: 'c'} >>> subkeys=[1,3] >>> def sub_dict(d,subkeys): return dict([(k,d.get(k)) for k in subkeys if k in d]) >>> print sub_dict(dict1,subkeys) {1: 'a', 3: 'c'}
C、反转字典,也就是key变成新字典的value,value变成新字典的key(注意,如果value值有重复,反转后的字典就只会保留一个
>>> def invert_dict(d): return dict([(k,v) for v,k in d.iteritems()]) >>> print invert_dict(dict1) {'a': 1, 'c': 3, 'b': 2} >>>
1) has_key(key) 判断key是否在字典中
2)copy()返回一个字典的副本(该复制是一个浅复制)
>>> d2={1:[1],2:[2],3:[3]} >>> d3=d2.copy() >>> d3[1].append(4) >>> d2[1] [1, 4]
如果要深复制的话,就要用到copy.deepcopy(a)
>>> d2={1:[1],2:[2],3:[3]} >>> import copy >>> d3=copy.deepcopy(d2) >>> d3[1].append(4) >>> print d2[1] , d3[1] [1] [1, 4]
3)clear( ) 清空dict
4)update(d) 用一个字典来跟新另外一个字典,有点类似与2个字典的合并
>>> dict1={1: 'a', 2: 'b', 3: 'c'} >>> dict2={1:'x',4:'y'} >>> dict1.update(dict2) >>> dict1 {1: 'x', 2: 'b', 3: 'c', 4: 'y'} >>>
二、遍历
字典的遍历方法很多
1、直接利用dict
>>> d {'a': 'aa', 'c': 'cc', 'b': 'bb'} >>> for i in d: print i,d[i] a aa c cc b bb
2、利用items()
>>> for i,v in d.items(): print i,v a aa c cc b bb
当然也可以这样
>>> for (i,v) in d.items(): print i,v a aa c cc b bb
3、iteritems()
(我觉得比较好的方法)
>>> for k,v in d.iteritems(): print k,v a aa c cc b bb
三、一些进阶用法
1、一键多值
一般情况,字典都是一对一映射的,但如果我们需要一对多的映射,比如一本书,我们要统计一些单词出现的页数。那么,可以用list作为dict的value值。在利用setdefault()方法就可以完成
>>> d={'hello':[1,4,9],"good":[1,3,6]} >>> d {'good': [1, 3, 6], 'hello': [1, 4, 9]} >>> d.setdefault('good',[]).append(7) >>> d {'good': [1, 3, 6, 7], 'hello': [1, 4, 9]} >>> d.setdefault('bad',[]).append(2) >>> d {'bad': [2], 'good': [1, 3, 6, 7], 'hello': [1, 4, 9]} >>>
当然,如果写成一个函数话,就可以更方便的使用,
我们也可以利用set来代替list
>>> def addFunc(d,word,pag): d.setdefault(word,set()).add(pag) >>> d={'hello':set([1,4,9]),"good":set([1,3,6])} >>> addFunc(d,'hello',8) >>> d {'good': set([1, 3, 6]), 'hello': set([8, 1, 4, 9])} >>> addFunc(d,'bad',8) >>> d {'bad': set([8]), 'good': set([1, 3, 6]), 'hello': set([8, 1, 4, 9])}
2、利用字典完成简单工厂模式
字典的value不单单只是一些常见的字符串,数值,还可以是类和方法,比如我们就可以这样来实现简单工厂模式
>>> class cat(object): def __init__(self): print 'cat init' >>> class dog(object): def __init__(self): print 'dag init' >>> d={'cat':cat,'dog':dog} >>> def factoryFunc(d,name): if name in d: return d[name]() else: raise Exception("error") >>> cat=factoryFunc(d,'cat') cat init
>>> def deal_cat(): print 'cat run!!' >>> def deal_dog(): print 'dag run!!' >>> d={'cat':deal_cat ,'dog':deal_dog } >>> animal='cat' >>> d[animal]() cat run!!

The article discusses Python's new "match" statement introduced in version 3.10, which serves as an equivalent to switch statements in other languages. It enhances code readability and offers performance benefits over traditional if-elif-el

Exception Groups in Python 3.11 allow handling multiple exceptions simultaneously, improving error management in concurrent scenarios and complex operations.

Function annotations in Python add metadata to functions for type checking, documentation, and IDE support. They enhance code readability, maintenance, and are crucial in API development, data science, and library creation.

The article discusses unit tests in Python, their benefits, and how to write them effectively. It highlights tools like unittest and pytest for testing.

Article discusses access specifiers in Python, which use naming conventions to indicate visibility of class members, rather than strict enforcement.

Article discusses Python's \_\_init\_\_() method and self's role in initializing object attributes. Other class methods and inheritance's impact on \_\_init\_\_() are also covered.

The article discusses the differences between @classmethod, @staticmethod, and instance methods in Python, detailing their properties, use cases, and benefits. It explains how to choose the right method type based on the required functionality and da

InPython,youappendelementstoalistusingtheappend()method.1)Useappend()forsingleelements:my_list.append(4).2)Useextend()or =formultipleelements:my_list.extend(another_list)ormy_list =[4,5,6].3)Useinsert()forspecificpositions:my_list.insert(1,5).Beaware


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6
Visual web development tools

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools
