<p>在将值添加到<code>a</code>之前,可以执行循环并检查<code>b</code>中的每个键</p>
<pre class="lang-py prettyprint-override"><code>def add_dict(a,b):
for key in b:
if key not in a:
a[key] = b[key]
return a
</code></pre>
<hr/>
<p>编辑:如果希望保留来自<code>b</code>而不是<code>a</code>的某些值,即使键已经在<code>a</code>中,也可以使用键列表向<code>add_dict</code>添加第三个参数。然后在循环中,检查键是否在此列表中,如果是,则使用来自<code>b</code>的值而不是<code>a</code>的值</p>
<p>这导致(为了清晰起见,我添加了一个NumPy样式的docstring)</p>
<pre class="lang-py prettyprint-override"><code>def add_dict(a,b, force_add=None):
"""
Add key/value pairs from `b` into `a`. If a key is in `a` and in `b` its
value is not added to `a`, unless it is in force_add`.
Note: this modifies dictionary `a`
Parameters
a : dict
The first dictionary
b : dict
The second dictionary
force_add : list, optional
A list of keys in `b` whole values will be added to `a` even if `a`
already has the key
Returns
-
dict
The first dictionary after it was modified.
"""
if force_add is None:
force_add = []
for key in b:
if key not in a or key in force_add:
a[key] = b[key]
return a
</code></pre>
<p>现在如果你做<code>add_dict(b, a, force_add=["saya"])</code>,你会得到</p>
<pre><code>{'omnibus': 0, 'law': 0, 'meningkatkan': 0, 'kesejahteraan': 0, 'saya': 2, 'setuju': 0, 'diterapkan': 0, 'menolak': 2, 'dan': 1, 'tetap': 1, 'di': 1, 'sekolah': 1, 'diperintahkan': 1, 'untuk': 1, 'tidak': 1, 'layak': 1}
</code></pre>