现有两个字典dict如下:
dict1={1:[1,11,111],2:[2,22,222]}dict2={3:[3,33,333],4:[4,44,444]}合并两个字典得到类似:
{1:[1,11,111],2:[2,22,222],3:[3,33,333],4:[4,44,444]}方法1:
dictMerged1=dict(dict1.items()+dict2.items())方法2:
dictMerged2=dict(dict1, **dict2)方法2等同于:
dictMerged=dict1.copy()dictMerged.update(dict2)或者:
dictMerged=dict(dict1)dictMerged.update(dict2)方法2比方法1速度快很多,用timeit测试如下
[root@localhost ~]# python -m timeit -s 'dict1=dict2=dict((i,i) for i in range(100))' 'dictMerged1=dict(dict1.items()+dict2.items())'100000 loops, best of 3: 16.4 usec per loop[root@localhost ~]# python -m timeit -s 'dict1=dict2=dict((i,i) for i in range(100))' 'dictMerged2=dict(dict1,**dict2)'100000 loops, best of 3: 5.84 usec per loop[root@localhost ~]# 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: 6.07 usec per loop[root@localhost ~]# 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: 5.84 usec per loop