本文实例讲述了python中实现两个字典(dict)合并的方法,分享给大家供大家参考。具体方法如下:
现有两个字典dict如下:
?12 dict1={1:[1,11,111],2:[2,22,222]} dict2={3:[3,33,333],4:[4,44,444]}
合并两个字典得到类似:
?1 {1:[1,11,111],2:[2,22,222],3:[3,33,333],4:[4,44,444]}
方法1:
?1 dictmerged1=dict(dict1.items()+dict2.items())
方法2:
?1 dictmerged2=dict(dict1, **dict2)
方法2等同于:
?12 dictmerged=dict1.copy() dictmerged.update(dict2)
或者:
?12 dictmerged=dict(dict1) dictmerged.update(dict2)
方法2比方法1速度快很多,用timeit测试如下
?12345678 $ python -m timeit -s 'dict1=dict2=dict((i,i) for i in range(100))' 'dictmerged1=dict(dict1.items()+dict2.items())' 10000 loops, best of 3: 20.7 usec per loop $ python -m timeit -s 'dict1=dict2=dict((i,i) for i in range(100))' 'dictmerged2=dict(dict1,**dict2)' 100000 loops, best of 3: 6.94 usec per loop $ python -m timeit -s 'dict1=dict2=dict((i,i) for i in range(100))' 'dictmerged3=dict(dict1)' 'dictmerged3.update(dict2)' 100000 loops, best of 3: 7.09 usec per loop $ python -m timeit -s 'dict1=dict2=dict((i,i) for i in range(100))' 'dictmerged4=dict1.copy()' 'dictmerged4.update(dict2)' 100000 loops, best of 3: 6.73 usec per loop