You need to enable JavaScript to run this app. Python查询字典中所有相同值对应键时仅返回首个结果的问题
优惠活动
大模型
产品
解决方案
定价
更多

Python查询字典中所有相同值对应键时仅返回首个结果的问题

问题解答

错误原因

你的代码在if cont == containers的判断块里直接执行了return matching_recipes,程序第一次匹配到符合条件的食谱完成追加操作后,就会直接触发函数返回,终止整个循环和函数运行,因此不会遍历字典剩下的元素。

修正后的代码

recipes = {'Fixate Pasta E Fagioli' : '1G1Y1t' , 'Fixate Vegan Quinoa with Winter Veggies' : 
'1G1Y1t' , 'Fixate Balsamic Mushroom Toast' : '1G1Y1t' }

def get_recipe(cont):
    matching_recipes = []
    for recipe, containers in recipes.items():
        if cont == containers:
            matching_recipes.append(recipe)
    return matching_recipes if matching_recipes else 'no matching recipe'

print(get_recipe('1G1Y1t'))

核心修改点

  • 将matching_recipes移到函数内部作为局部变量,避免多次调用函数时全局变量累计旧结果导致逻辑错误
  • 将return语句移出循环体,等待字典全部元素遍历完成后再统一返回最终的匹配结果

运行修正后的代码,传入'1G1Y1t'参数即可得到全部3个匹配的食谱列表。

内容的提问来源于stack exchange,提问作者mlkurek711

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 08:33:01