在新函数中,如何从 Python 中传入的字典返回 KEY?

问题描述 投票:0回答:1

我创建了一个请求两个参数的函数,第二个参数(current_resource)从超出范围的字典中获取一个值,并将该值与用户请求进行比较。我将值作为 f 字符串返回,但我想要返回键,而不是返回值。

功能:

def check_resources(order, current_resource):
    """Checks if resources are greater than the items requirements. If so, returns order. Or Returns missing req."""
    if order > current_resource:
        return f"Sorry there is not enough {current_resource}"
    elif current_resource > order:
        return f"Okay, here is your order."

请求代码:

print(check_resources(MENU["espresso"]["ingredients"]["water"], current_inventory["water"]))

它正在检查存储了键和值的字典,在上面的例子中,我将其与“水”的值进行比较。当返回时,它返回一个 INT 形式的值。

我正在寻找在 F 字符串中返回键名称的方法。

我尝试过使用 .key() 方法,例如:

current_resource.key()

但它返回错误:

AttributeError:“int”对象没有属性“key”。

python dictionary return attributeerror f-string
1个回答
0
投票

您仅将值发送给函数,因此您无法取回密钥:

def check_resources(order, current_resource):
    print(order, current_resource)
    """Checks if resources are greater than the items requirements. If so, returns order. Or Returns missing req."""
    if int(order) > int(current_resource):
        return f"Sorry there is not enough {current_resource} "
    elif int(current_resource) > int(order):
        return f"Okay, here is your order."

current_inventory = {"water": "120"}
MENU = {"espresso" : "2","ingredients" : "2", "water" : "100"}
print(check_resources(MENU["water"], current_inventory["water"]))

current_inventory = {"water": "120"}
MENU = {"espresso" : "2","ingredients" : "2", "water" : "200"}
print(check_resources(MENU["water"], current_inventory["water"]))

输出:

100 120
Okay, here is your order.
200 120
Sorry there is not enough 120 

你的字典输入看起来怎么样?

© www.soinside.com 2019 - 2024. All rights reserved.