<p>我正在整理一本字典,并试图通过它来确定“food\u type”中哪个字典键对应的值是“fruit”。到目前为止,我在下面的代码中最远的部分是:</p>
<pre><code>def fruit (food_type):
for f in food_type.values():
if f=="fruit" :
return(f)
fruit ({'apple': 'fruit', 'lettuce': 'veggie', 'banana':'fruit'})
</code></pre>
<p>它只返回“fruit”一次,所以如果这是我在本例中想要的,我不是100%,因为我的最终目标是将值反映回字典,并返回值为“fruit”的键。我知道为了得到一个值,你可以这样做:d[k]或d.get(k)等等</p>
<p>我正在为此查找以下输出:</p>
<pre><code>["apple","banana"]
</code></pre>
<p>这可能就是你想要的:</p>
<pre><code>def fruit (food_type):
return [k for k in food_type if food_type[k] == "fruit"]
print fruit ({'apple': 'fruit', 'lettuce': 'veggie', 'banana':'fruit'})
# ['apple', 'banana']
</code></pre>