You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

首次使用Python遇TypeError:'dict'对象不可调用问题求助

Fixing "TypeError: 'dict' object is not callable" in Your Dictionary Translation Code

Hey there! Let's sort out this error you're seeing. The problem is super straightforward once you spot it.

What's Going Wrong?

When you load your JSON file with json.load(), the data variable becomes a dictionary (Python's key-value store). In your translateWord function, you wrote return data(w)—this tries to call data like it's a function, but dictionaries don't support that syntax. To pull a value from a dictionary using its key, you need to use square brackets [] instead of parentheses ().

Corrected Basic Code

Here's the fixed version of your code, with the key change marked:

import json
data = json.load(open("data.json"))

def translateWord(w):
    # Changed from data(w) to data[w]
    return data[w]

word = input("Enter word: ")
print(translateWord(word))

Quick Improvement: Handle Case Sensitivity

Chances are your JSON dictionary uses lowercase keys (like "rain" instead of "Rain"). If a user enters a capitalized word, you'll get a KeyError. Let's fix that by converting the input to lowercase:

import json
data = json.load(open("data.json"))

def translateWord(w):
    # Convert input to lowercase to match dictionary keys
    return data[w.lower()]

word = input("Enter word: ")
print(translateWord(word))

Bonus: Avoid Errors for Missing Words

If someone enters a word that isn't in your dictionary, the code will throw another error. Let's add a safety net using the dictionary's get() method, which lets you return a custom message if the key doesn't exist:

import json
data = json.load(open("data.json"))

def translateWord(w):
    w_lower = w.lower()
    # Return the definition, or a friendly message if the word isn't found
    return data.get(w_lower, f"Oops, we don't have '{w}' in our dictionary yet!")

word = input("Enter word: ")
print(translateWord(word))

内容的提问来源于stack exchange,提问作者Bokchee 88

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:49:39