Python新手求助:如何读取JSON键值并无格式输出词典内容
Hey there! Let's break down what's going wrong and fix this step by step.
What's Causing the KeyError?
Your error comes from this line: currentword[search]['English Word', 'Definition', 'Use case example']. Python dictionaries don't let you use a tuple of multiple keys to fetch values all at once—it treats ('English Word', 'Definition', 'Use case example') as a single, non-existent key in your JSON, hence the KeyError.
And to confirm your understanding: Yes, "Bonjour" is a top-level key in your JSON, and it maps to a sub-dictionary where "English Word", "Definition", etc., are all valid keys. You got that part right!
Fixing the Code & Formatting Output
We'll first grab the sub-dictionary for your target word, then loop through the fields you want to display, pulling each key-value pair and formatting it cleanly (no JSON brackets or quotes in sight).
Here's the corrected, full code example:
import json search = "Bonjour" # User's input word # Load your JSON file with open("your_dictionary_file.json", "r") as data: currentword = json.load(data) # Get the sub-dictionary for the searched word target_entry = currentword[search] # List of fields you want to show desired_fields = ['English Word', 'Definition', 'Use case example'] # Loop through fields and print in your desired format for field in desired_fields: # Optional: Add a check to avoid errors if a field is missing if field in target_entry: print(f"{field} - {target_entry[field]}") else: print(f"{field} - No data available")
What This Does
currentword[search]grabs all the definition data for "Bonjour" (that inner dictionary from your JSON).- We loop through your list of desired fields, pulling each value from the sub-dictionary one by one.
- The f-string
f"{field} - {target_entry[field]}"formats the output exactly how you want it: clean, human-readable text without any JSON syntax.
Bonus: Robustness for Missing Fields
The if field in target_entry check is a nice touch for a beginner project—it prevents your code from crashing if some word in your dictionary is missing a field (like no "Use case example"), and instead shows a friendly fallback message.
内容的提问来源于stack exchange,提问作者Flexy

