擅长:python、mysql、java
<p>你很接近。</p>
<pre><code>idnum = 11
# The loop and 'if' are good
# You just had the 'break' in the wrong place
for id, idnumber in A.iteritems():
if idnum in idnumber.keys(): # you can skip '.keys()', it's the default
calculate = some_function_of(idnumber[idnum])
break # if we find it we're done looking - leave the loop
# otherwise we continue to the next dictionary
else:
# this is the for loop's 'else' clause
# if we don't find it at all, we end up here
# because we never broke out of the loop
calculate = your_default_value
# or whatever you want to do if you don't find it
</code></pre>
<p>如果需要知道内部有多少个<code>11</code>键,可以:</p>
<pre><code>idnum = 11
print sum(idnum in idnumber for idnumber in A.itervalues())
</code></pre>
<p>这是因为密钥只能在每个<code>dict</code>中出现一次,所以您只需测试密钥是否存在。<code>in</code>返回<code>True</code>或<code>False</code>,等于<code>1</code>和<code>0</code>,因此<code>sum</code>是<code>idnum</code>的出现次数。</p>