python - 交互式字典,TypeError:'dict'不可调用?
问题描述
import json
data = json.load(open("files1\data.json"))
def definitioner(w):
return data(w)
word = input("Enter the word you are looking for: ")
print(definitioner(word))
我正在上 UDEMY 上一门课程,在自己尝试之后它没有用,所以我什至复制了代码以查看它是否是我的代码,无法弄清楚问题是什么,任何帮助将不胜感激。我正在运行 Python 3.8 谢谢。
解决方案
你调用data(w)
它就像它是一个函数,但它data
是一个字典。改用data.get(w)
:
def definitioner(w):
return data.get(w)
这还允许您通过添加第二个参数来指定如果该单词不存在时默认返回的内容:
def definitioner(w):
return data.get(w, 'Word not found!')
推荐阅读
- html - 背景颜色和边框半径之间的空白
- sql - SQL根据条件将值从一列复制到另一列
- c# - 如何从现有的 Windows 服务启动 AspNetCore 应用程序
- php - 用php调用sql函数
- intellij-idea - 是否可以在 Intellij IDEA 中将选择拆分为多个光标?
- python - 通过对象从 QuerySet 中获取下一个和上一个对象
- javascript - 动态翻译数据 react localize redux
- scala - 如何将 Scala 枚举用于 JOOQ 转换器
- sql - oracle sql 内联查询标识符无效
- django - 如何使用动态更新的 Choicefield 验证表单集?