如何连接两个字典创建一个新的?

假设我有三个字典

d1={1:2,3:4}
d2={5:6,7:9}
d3={10:8,13:22}

如何创建一个新的d4来组合这三个字典?例如:

d4={1:2,3:4,5:6,7:9,10:8,13:22}
533788 次浏览

在python 2中:

d4 = dict(d1.items() + d2.items() + d3.items())

在python3中(应该更快):

d4 = dict(d1)
d4.update(d2)
d4.update(d3)

前一个SO问题,这两个答案都来自在这里

你可以使用update()方法来构建一个包含所有项的新字典:

dall = {}
dall.update(d1)
dall.update(d2)
dall.update(d3)

或者,在循环中:

dall = {}
for d in [d1, d2, d3]:
dall.update(d)
  1. 最慢且在Python3中不起作用:连接items并在结果列表中调用dict:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = dict(d1.items() + d2.items() + d3.items())'
    
    
    100000 loops, best of 3: 4.93 usec per loop
    
  2. Fastest: exploit the dict constructor to the hilt, then one update:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = dict(d1, **d2); d4.update(d3)'
    
    
    1000000 loops, best of 3: 1.88 usec per loop
    
  3. Middling: a loop of update calls on an initially-empty dict:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = {}' 'for d in (d1, d2, d3): d4.update(d)'
    
    
    100000 loops, best of 3: 2.67 usec per loop
    
  4. Or, equivalently, one copy-ctor and two updates:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = dict(d1)' 'for d in (d2, d3): d4.update(d)'
    
    
    100000 loops, best of 3: 2.65 usec per loop
    

I recommend approach (2), and I particularly recommend avoiding (1) (which also takes up O(N) extra auxiliary memory for the concatenated list of items temporary data structure).

下面是一行语句(imports don't count:),可以很容易地概括为连接N个字典:

Python 3

from itertools import chain
dict(chain.from_iterable(d.items() for d in (d1, d2, d3)))

和:

from itertools import chain
def dict_union(*args):
return dict(chain.from_iterable(d.items() for d in args))

Python 2.6 &2.7

from itertools import chain
dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3))

输出:

>>> from itertools import chain
>>> d1={1:2,3:4}
>>> d2={5:6,7:9}
>>> d3={10:8,13:22}
>>> dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3)))
{1: 2, 3: 4, 5: 6, 7: 9, 10: 8, 13: 22}

推广到连接N个字典:

from itertools import chain
def dict_union(*args):
return dict(chain.from_iterable(d.iteritems() for d in args))

我知道我来晚了一点,但我希望这能帮到别人。

使用dict构造函数

d1={1:2,3:4}
d2={5:6,7:9}
d3={10:8,13:22}


d4 = reduce(lambda x,y: dict(x, **y), (d1, d2, d3))

作为一个函数

from functools import partial
dict_merge = partial(reduce, lambda a,b: dict(a, **b))

使用__abc0方法可以消除创建中间字典的开销:

from functools import reduce
def update(d, other): d.update(other); return d
d4 = reduce(update, (d1, d2, d3), {})