<p>您可以使用<a href="https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects">dictionary view</a>:</p>
<pre><code># Python 2
if first.viewitems() <= second.viewitems():
# true only if `first` is a subset of `second`
# Python 3
if first.items() <= second.items():
# true only if `first` is a subset of `second`
</code></pre>
<p>字典视图是<a href="https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects">standard in Python 3</a>,在Python 2中,您需要在标准方法前面加上<code>view</code>。它们的行为类似于集合,并且<code><=</code>测试其中一个是否是另一个集合的子集(或等于)。</p>
<p>Python3中的演示:</p>
<pre><code>>>> first = {"one":"un", "two":"deux", "three":"trois"}
>>> second = {"one":"un", "two":"deux", "three":"trois", "foo":"bar"}
>>> first.items() <= second.items()
True
>>> first['four'] = 'quatre'
>>> first.items() <= second.items()
False
</code></pre>
<p>这也适用于<em>不可散列值</em>,因为键使键值对已经是唯一的。文档在这一点上有点混乱,但即使使用可变值(比如列表),也可以:</p>
<pre><code>>>> first_mutable = {'one': ['un', 'een', 'einz'], 'two': ['deux', 'twee', 'zwei']}
>>> second_mutable = {'one': ['un', 'een', 'einz'], 'two': ['deux', 'twee', 'zwei'], 'three': ['trois', 'drie', 'drei']}
>>> first_mutable.items() <= second_mutable.items()
True
>>> first_mutable['one'].append('ichi')
>>> first_mutable.items() <= second_mutable.items()
False
</code></pre>
<p>您还可以将<a href="https://docs.python.org/2/library/functions.html#all">^{<cd3>} function</a>与生成器表达式一起使用;使用<code>object()</code>作为哨兵来简明地检测丢失的值:</p>
<pre><code>sentinel = object()
if all(first[key] == second.get(key, sentinel) for key in first):
# true only if `first` is a subset of `second`
</code></pre>
<p>但这并不像使用字典视图那样可读和表达能力强。</p>