You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现字典键取值函数:存在返回对应值,不存在返回指定提示

解决字典键值查询的函数问题

原代码存在几个明显问题,导致无法得到期望输出:

  • 遍历字典时,每碰到不匹配的键就打印提示,会重复输出多次Fruit Not Found
  • 判断条件用了x in k,这是模糊匹配(比如传'emo'也会匹配'Lemon'),但需求是精确匹配键
  • 匹配成功时往列表里加的是键x,不是对应的值v
  • 用列表存储完全多余,字典的键是唯一的,找到匹配直接返回值就行

修正后的代码(简洁版)

利用字典自带的get方法,一行就能实现需求:

fruits = {"Apple": 8, "Orange": 7, "Lemon": 9, "Lime": 5, "Banana": 20}

def fruit_price(x):
    return fruits.get(x, 'Fruit Not Found')

# 测试
print(fruit_price('Lemon'))  # 输出9
print(fruit_price('Grape'))  # 输出Fruit Not Found

对应原步骤的实现版

如果要严格按照你给出的步骤来写,调整后的代码如下:

fruits = {"Apple": 8, "Orange": 7, "Lemon": 9, "Lime": 5, "Banana": 20}

def fruit_price(x):
    price = []
    for k, v in fruits.items():
        if x == k:  # 改成精确匹配键
            price.append(v)  # 添加对应的值而非键
            break  # 找到唯一匹配后直接终止遍历,提升效率
    # 遍历结束后判断列表是否有值
    return price[0] if price else 'Fruit Not Found'

# 测试
print(fruit_price('Lemon'))  # 输出9
print(fruit_price('Grape'))  # 输出Fruit Not Found

这样不管是存在的键还是不存在的键,都能返回符合需求的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 19:30:00