首页 > 解决方案 > 交互式字典,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 谢谢。

标签: pythonpython-3.xdictionary

解决方案


你调用data(w)它就像它是一个函数,但它data是一个字典。改用data.get(w)

def definitioner(w):
    return data.get(w)

这还允许您通过添加第二个参数来指定如果该单词不存在时默认返回的内容:

def definitioner(w):
    return data.get(w, 'Word not found!')

推荐阅读