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完全不受影响。

 

转载于:https://www.cnblogs.com/mzdu/p/4903221.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值