<p>最佳方法取决于您使用的Python版本。它们都涉及到对集合交集使用<code>&</code>运算符。在</p>
<ul>
<li>3.0+<code>dict.keys()</code>方法</li>
<li>2.7+<code>dict.viewkeys()</code>方法</li>
<li>2.3+<code>set</code>方法</li>
</ul>
<p><strong>数字键()</strong>3.0+</p>
<p>在Python3中,<code>dict.keys()</code>返回一个<a href="https://docs.python.org/dev/whatsnew/2.7.html#pep-3106-dictionary-views" rel="nofollow">^{<cd6>}</a>对象,该对象重写了amp;运算符[1]:</p>
<pre><code>x={1:'a', 2:'b', 3:'c'}
y={2:'beta', 3:'gamma', 4:'delta'}
for k in x.keys() & y.keys():
print(k, x[k], y[k])
</code></pre>
<p>输出:</p>
^{pr2}$
<p>但是在python2中,这将给您一个<code>TypeError</code>:</p>
<pre>
Traceback (most recent call last):
for k in x.keys() & y.keys():
TypeError: unsupported operand type(s) for &: 'list' and 'list'
</pre>
<p><strong>dict.view键()</strong>2.7+</p>
<p>不过,别着急!这个功能在2.7中被后移植到Python中,但是使用了不同的名称(以免破坏现有代码),<a href="https://docs.python.org/2/library/stdtypes.html#dict.viewkeys" rel="nofollow">^{<cd3>}</a>:</p>
<pre><code>for k in x.viewkeys() & y.viewkeys():
print k, x[k], y[k]
</code></pre>
<p>(相同输出)</p>
<p><strong>带集合</strong>2.3+</p>
<p>从2.3开始,您可以使用<a href="https://docs.python.org/2/library/sets.html" rel="nofollow">^{<cd9>}</a>,以及交集运算符。在</p>
<blockquote>
<p>s & t: new set with elements common to s and t</p>
</blockquote>
<p>例如:</p>
<pre><code>for k in set(x) & set(y):
print k, x[k], y[k]
</code></pre>
<p>(相同输出)</p>
<p>但是,在这里,您复制了键所占用的空间(一次在字典中,用作键,再一次在一个完全独立的<code>set</code>)中)</p>
<p>[1]<a href="https://www.python.org/dev/peps/pep-3106/" rel="nofollow">PEP-3106 Revamping dict.keys(), .values() and .items()</a></p>