Python函数如何返回字典键名而非传入的字典值?
解决方法:在函数中返回字典键名而非数值
你遇到的问题本质是传入函数的current_resource是字典的数值(int类型),不是字典本身或键值对,所以调用key()方法会报错——int对象没有这个属性。要返回对应的键名,需要把键名传递给函数,或者调整参数让函数能关联到键。
以下是几种可行的修改方式:
方式1:直接传入键名作为第三个参数
修改函数,新增一个参数接收资源的键名,直接在返回字符串中使用这个键名:
def check_resources(order, current_resource, resource_name): """检查资源是否满足订单需求,返回对应提示""" if order > current_resource: return f"Sorry there is not enough {resource_name}" # 将原代码的>改为>=,避免资源刚好满足时无返回 elif current_resource >= order: return f"Okay, here is your order."
调用时传入键名"water":
print(check_resources(MENU["espresso"]["ingredients"]["water"], current_inventory["water"], "water"))
方式2:传入库存字典和资源键名
如果不想每次单独传数值,可以直接把整个库存字典和资源键名传给函数,让函数内部获取数值:
def check_resources(order, inventory, resource_name): """检查资源是否满足订单需求,返回对应提示""" current_resource = inventory[resource_name] if order > current_resource: return f"Sorry there is not enough {resource_name}" elif current_resource >= order: return f"Okay, here is your order."
调用时简化参数:
print(check_resources(MENU["espresso"]["ingredients"]["water"], current_inventory, "water"))
方式3:批量检查多种资源(更实用的扩展)
如果你的订单需要多种原料(比如拿铁需要水、牛奶、咖啡豆),可以重构函数来处理整个配料字典,一次性检查所有资源:
def check_resources(order_ingredients, inventory): """批量检查库存是否满足所有配料需求,返回对应提示""" for item, required_amount in order_ingredients.items(): # 用get避免库存中无该原料时报错,默认值设为0 if inventory.get(item, 0) < required_amount: return f"Sorry there is not enough {item}" return f"Okay, here is your order."
调用时直接传入整个配料字典和库存字典:
print(check_resources(MENU["espresso"]["ingredients"], current_inventory))
内容的提问来源于stack exchange,提问作者Evan
相关产品推荐
相关产品推荐

