擅长:python、mysql、java
<p>这里有一个<em>字典理解</em>来使用<a href="https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable" rel="nofollow noreferrer">^{<cd1>}</a>和<a href="https://docs.python.org/3/library/functions.html#sum" rel="nofollow noreferrer">^{<cd2>}</a>实现这一点。在这里,我从所有三个dict创建了一个<a href="https://docs.python.org/3/library/stdtypes.html#set" rel="nofollow noreferrer">^{<cd3>}</a>键。然后我在<em>字典理解</em>中对该集合进行迭代,以获得每个<em>键</em>的<em>值的总和</p>
<pre><code>>>> from itertools import chain
>>> dict1 = {'a': 10, 'b': 8, 'c':3}
>>> dict2 = {'c': 4}
>>> dict3 = {'e':9, 'a':3}
>>> my_dicts = dict1, dict2, dict3
>>> {k: sum(dd.get(k, 0) for dd in my_dicts) for k in set(chain.from_iterable(d.keys() for d in my_dicts))}
{'a': 13, 'e': 9, 'b': 8, 'c': 7}
</code></pre>