首页 > 解决方案 > 从先前函数返回的字典中打印键

问题描述

我遇到了这个问题。不知道如何继续。

我的字典:

DICT = {
    "inside": "It's obviously inside",
    "outside": "It went outside"
}

我有一个返回字典键的函数。然后我有一个打印功能,应该打印连接到该功能的值。

如果我以前的函数的返回线是return "inside",我试过这个:

def print_location(key):
    print(DICT[key])

这似乎不起作用。不知何故,我可能需要将变量“键”连接到返回的键,但这是我卡住的地方。我怎么能这样做?

标签: python

解决方案


你的代码看起来不错;以下按预期工作:

DICT = {
    "inside": "It's obviously inside",
    "outside": "It went outside"
}

def get_key():
    return 'inside'

def print_location(key):
    print(DICT[key])

# run the code
the_key = get_key()
print_location(the_key)  # prints "It's obviously inside"

推荐阅读