在python 3.5中,我们可以使用double-splat解包来合并字典
>>> d1 = {1: 'one', 2: 'two'}
>>> d2 = {3: 'three'}
>>> {**d1, **d2}
{1: 'one', 2: 'two', 3: 'three'}
凉。但是,它似乎并未推广到动态用例:
>>> ds = [d1, d2]
>>> {**d for d in ds}
SyntaxError: dict unpacking cannot be used in dict comprehension
相反,我们必须这样做reduce(lambda x,y: {**x, **y}, ds, {})
,这看起来很丑陋。当该表达式似乎没有任何歧义时,为什么解析器不允许“一种明显的方法”?
这并不是您所提问题的确切答案,但我认为使用ChainMap
它是一种惯用而优雅的方式来完成您的建议(在线合并字典):
>>> from collections import ChainMap
>>> d1 = {1: 'one', 2: 'two'}
>>> d2 = {3: 'three'}
>>> ds = [d1, d2]
>>> dict(ChainMap(*ds))
{1: 'one', 2: 'two', 3: 'three'}
尽管这不是一个特别透明的解决方案,但是由于许多程序员可能并不确切知道其ChainMap
工作原理。请注意(如@AnttiHaapala所指出的),“使用了首次发现”,因此,根据您的意图,您可能需要先致电给,reversed
然后再将dict
传入ChainMap
。
>>> d2 = {3: 'three', 2:'LOL'}
>>> dict(ChainMap(*ds))
{1: 'one', 2: 'two', 3: 'three'}
>>> dict(ChainMap(*reversed(ds)))
{1: 'one', 2: 'LOL', 3: 'three'}