Python字典遍历后匹配键值输出错误问题排查求助
Hey there! Let's break down why your code is showing the wrong device details when you enter a valid item code.
The Root Cause
When you loop through device.items() with for key, value in device.items():, the value variable gets updated with each iteration. By the time the loop finishes, value is stuck holding the last entry in your dictionary (which is the value for RTLM). That's why no matter which valid code you enter, it always prints the details for RTLM—you're using the leftover value from the end of the loop, not the value tied to the code the user selected.
The Fix
Instead of relying on the value variable from the loop, you can directly access the correct value using the user's input (response) as the key for your device dictionary. Here's how to fix that problematic line:
Change this:
print("Item Code Chosen " + response + str(value))
To this:
print("Item Code Chosen " + response + str(device[response]))
Full Modified Code
Here's the complete corrected code so you can test it out:
device = { 'BPCM' : ['phone', 'Description: Compact', 'price', 29.99], 'BPSH' : ['phone', 'Description: Clam Shell', 'price', 49.99], 'RTMS' : ['Tablet', 'Description: RoboTab - 10-inch screen and 64GB memory', 'price', 299.99], 'RTLM' : ['Tablet', 'Description: RoboTab - 10-inch screen and 256 GB memory', 'price', 499.99], } print("Hello customer, here is your list of phone and tablet choices. Please choose a phone or tablet by entering your name and the item code:") for key, value in device.items(): print("\nItem Code: " + key) print(" " + str(value)) name = raw_input("\nPlease tell me your name? ") print("Hello " + name) response = raw_input("Please enter item code: ") if response in device.keys(): print("Item Code Chosen " + response + str(device[response])) else: print("This code " + response + " is not in our list, please try again or choose quit 'q'")
Now when you enter BPCM, it'll correctly pull the value associated with that key from the dictionary, showing the compact phone details instead of the last tablet's info.
内容的提问来源于stack exchange,提问作者Dac121




