当前位置: 代码迷 >> 综合 >> python中两个字典(dict)合并
  详细解决方案

python中两个字典(dict)合并

热度:19   发布时间:2023-12-14 09:34:03.0
  1. dict1={ 1:[1,11,111],2:[2,22,222]} 
  2. 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())

方法二:

  1. dictMerged2=dict(dict1, **dict2)

方法2等同于:

  1. dictMerged=dict1.copy() 
  2. dictMerged.update(dict2)

或者

  1. dictMerged=dict(dict1) 
  2. dictMerged.update(dict2)

方法2比方法1速度快很多,用timeit测试如下

  1. $ python -m timeit -s 'dict1=dict2=dict((i,i) for i in range(100))' 'dictMerged1=dict(dict1.items()+dict2.items())'
  2. 10000 loops, best of 3: 20.7 usec per loop
  3. $ python -m timeit -s 'dict1=dict2=dict((i,i) for i in range(100))' 'dictMerged2=dict(dict1,**dict2)'
  4. 100000 loops, best of 3: 6.94 usec per loop
  5. $ python -m timeit -s 'dict1=dict2=dict((i,i) for i in range(100))' 'dictMerged3=dict(dict1)' 'dictMerged3.update(dict2)'
  6. 100000 loops, best of 3: 7.09 usec per loop
  7. $ python -m timeit -s 'dict1=dict2=dict((i,i) for i in range(100))' 'dictMerged4=dict1.copy()' 'dictMerged4.update(dict2)'
  8. 100000 loops, best of 3: 6.73 usec per loop