<p>使用集合和事物,还可以合并任意数量的词典:</p>
<pre><code>from functools import reduce
import operator
# Usage: merge(a, b, ...)
def merge(*args):
# Make a copy of the input dicts, can be removed if you don't care about modifying
# the original dicts.
args = list(map(dict.copy, args))
# Dict to store the result.
out = {}
for k in reduce(operator.and_, map(dict.keys, args)): # Python 3 only, see footnotes.
# Use `.pop()` so that after the all elements of shared keys have been combined,
# `args` becomes a list of disjoint dicts that we can merge easily.
vs = [d.pop(k) for d in args]
if isinstance(vs[0], dict):
# Recursively merge nested dicts
common = merge(*vs)
else:
# Use a set to collect unique values
common = set(vs)
# If only one unique value, store that as is, otherwise use a list
common = next(iter(common)) if len(common) == 1 else list(common)
out[k] = common
# Merge into `out` the rest of the now disjoint dicts
for arg in args:
out.update(arg)
return out
</code></pre>
<p>假设要合并的每个字典具有相同的“结构”,因此<code>"owns"</code>不能是<code>a</code>中的列表和{<cd3>}中的dict。dict的每个元素也需要是散列的,因为这个方法使用集合来聚合唯一的值。在</p>
<hr/>
<p>下面的代码只适用于python3,因为在python2中,<code>dict.keys()</code>返回一个普通的旧列表。在</p>
^{pr2}$
<p>另一种方法是添加一个额外的<code>map()</code>,将列表转换为集合:</p>
<pre><code>reduce(operator.and_, map(set, map(dict.keys, args)))
</code></pre>