假设我有三个字典
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}
假设我有三个字典
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}
在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)
Slowest and doesn't work in Python3: concatenate the items and call dict on the resulting list: $ 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 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 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 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
我推荐使用方法(2),并特别建议避免使用方法(1)(这也会占用O(N)个额外的辅助内存,用于连接项的临时数据结构列表)。
下面是一行语句(导入不算数:),可以很容易地概括为连接N个字典:
Python 3
from itertools import chain
dict(chain.from_iterable(d.items() for d in (d1, d2, d3)))
and:
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))
使用dict.update()方法可以消除创建中间字典的开销:
from functools import reduce
def update(d, other): d.update(other); return d
d4 = reduce(update, (d1, d2, d3), {})