Jupyter Notebook中KeyError排查与Fruit360代码报错求助
Hey there, let's break down your problem and fix it step by step!
The error message clearly points out that the string 'C:\Users\Msi\Desktop\KaggleDataset\fruits-360_dataset\fruits-360\Test\Apple Braeburn' isn’t a key in your label_to_id_dict.
Chances are, your label_to_id_dict uses fruit category names (like "Apple Braeburn") as keys, but your Test_labels list contains full folder paths instead. When you try to look up the full path in the dictionary, it can’t find a match—hence the KeyError.
Here’s how to adjust your code to align with the dictionary’s keys:
Step 1: Extract the Fruit Category Name from the Path
Use Python’s os.path.basename() to pull just the folder name (which is the fruit category) from each path in Test_labels:
import os # Clean up Test_labels to get only the fruit category name Test_labels_cleaned = [os.path.basename(x) for x in Test_labels] # Now convert to IDs using the cleaned labels Test_label_ids = np.array([label_to_id_dict[x] for x in Test_labels_cleaned])
Step 2: Verify Matching Formats
If you still get an error, check that the cleaned labels match the dictionary’s key format exactly (case, spaces, underscores all matter!). Print a few examples to compare:
# Print first 5 keys from your dictionary to check format print(list(label_to_id_dict.keys())[:5]) # Print first 5 cleaned labels to match print(Test_labels_cleaned[:5])
If there’s a mismatch (e.g., dictionary uses "apple_braeburn" but your cleaned label is "Apple Braeburn"), standardize both:
# Standardize cleaned labels: lowercase + replace spaces with underscores Test_labels_cleaned = [os.path.basename(x).lower().replace(" ", "_") for x in Test_labels] # Update the dictionary to match the same format label_to_id_dict = {k.lower().replace(" ", "_"): v for k, v in label_to_id_dict.items()}
Beyond this specific case, here are go-to steps for debugging KeyErrors in Jupyter:
- Find exactly which keys are missing: Before running the line that errors, print out elements in your list that aren’t in the dictionary:
missing_keys = [x for x in Test_labels if x not in label_to_id_dict] print("Missing keys (first 10):", missing_keys[:10]) - Check for hidden characters or data type mismatches: Use
repr()to see the raw string (including hidden spaces/newlines) and confirm data types:# Inspect the first missing key's raw representation print(repr(missing_keys[0])) # Check if the key and dictionary keys are the same type print(type(missing_keys[0]), type(list(label_to_id_dict.keys())[0])) - Use
dict.get()to avoid crashes (temporarily): If you need to bypass errors to debug further, useget()to return a default value for missing keys:# Return -1 for any missing key (adjust default as needed) Test_label_ids = np.array([label_to_id_dict.get(x, -1) for x in Test_labels]) # Then find which indices have invalid IDs invalid_indices = np.where(Test_label_ids == -1)[0] print("Invalid label indices (first 10):", invalid_indices[:10])
内容的提问来源于stack exchange,提问作者Pranesh Tamang

