Python中的collections库,dictionary的复制
Recall: list的使用和list的复制
list1 = [1,2,3] list2 = list1 list1[1] = 11 print list1 # [1,11,3] print list2 # [1,11,3]
当修改list1中的一个值,list2中的值也随即被修改了。
解决方法:
- list2 = [element for element in list1]
- 快速解决方法 list2 = list1[:]
问题回到在使用dictionary时,当某一key不存在时而直接使用,会抛出异常
解决方法,使用defaultdict
1 from collections import defaultdict 2 3 dict1 = defaultdict(int/str/list) 4 dict1['one'] # 0/''/[]
其实为了避免抛出异常,不使用defaultdict也可以使用dictionary本身自带的get方法取值
1 dict2 = dict() 2 dict2['one'] 3 4 >>> dict2['one'] 5 Traceback (most recent call last): 6 File "<stdin>", line 1, in <module> 7 KeyError: 'one' 8 9 # 如果不用0则默认返回None,get方法的使用与Java相同 10 dict2.get('one', 0) 11 >>> 0
前文降到了如何快速复制一个list,这里我们也连带着一起讲讲如何复制dictionary
解决方法:使用copy库
1 dict1 = {'one':1, 'two':2, 'three':[1, 2, 4]} 2 3 from copy import copy, deepcopy 4 5 dict2 = copy(dict1) 6 dict3 = deepcopy(dict1) 7 8 >>> dict1['three'].append(32) 9 >>> dict1 10 defaultdict(<type 'int'>, {'three': [1, 2, 4, 32], 'two': 2, 'one': 1}) 11 >>> dict2 12 defaultdict(<type 'int'>, {'one': 1, 'three': [1, 2, 4, 32], 'two': 2}) 13 >>> dict3 14 defaultdict(<type 'int'>, {'one': 1, 'three': [1, 2, 4], 'two': 2})
对dict1['three']元素进行了修改,则dict2的值也被修改了,dict3中的list完全不受影响。