python - 从先前函数返回的字典中打印键
问题描述
我遇到了这个问题。不知道如何继续。
我的字典:
DICT = {
"inside": "It's obviously inside",
"outside": "It went outside"
}
我有一个返回字典键的函数。然后我有一个打印功能,应该打印连接到该功能的值。
如果我以前的函数的返回线是return "inside"
,我试过这个:
def print_location(key):
print(DICT[key])
这似乎不起作用。不知何故,我可能需要将变量“键”连接到返回的键,但这是我卡住的地方。我怎么能这样做?
解决方案
你的代码看起来不错;以下按预期工作:
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"
推荐阅读
- javascript - 如何重构反应中的方法?
- excel - Excel (2010) 将格式化值转换为其等效文本
- awk - 如何用awk跳过两个模式之间的行?
- css - 谷歌自动完成出现在 reactstrap 模式后面
- python - 如何在字典中获取列表值
- go - 有没有办法从 reflect.Func 中提取包路径?
- docker - 如何配置 docker-compose 以便将磁盘挂载到文件夹,而不是本地磁盘
- docker - 无法从主机访问运行 docker 容器(本地主机:8081)
- openssl - HMAC 的 OpenSSL 速度命令
- apache-spark - 数据集中的分割数超过数据集分割限制,Dremio+Hive+Spark