如何在Python字典中使用input()函数获取的用户输入作为值?
Absolutely! You can use the return value of Python's input() function as values in a dictionary—your code is actually valid, and the issue you're seeing is likely a misunderstanding of how the code executes.
Let's break down what's happening with your code:
dictionary = {'1': input('Choose: [1]Red [2]Blue'), '2':input('Choose: [1]Green [2]Yellow')}
When this line runs, Python executes the input() calls in order:
- First, it displays the first prompt
Choose: [1]Red [2]Blue, waits for you to enter a value and press Enter. - Then, it displays the second prompt
Choose: [1]Green [2]Yellow, waits for your second input and Enter. - Only after both inputs are received does it create the dictionary with both values.
If you're only seeing the first input's result, it's probably because you haven't completed the second input yet, or you're not inspecting the full dictionary afterward. To confirm the dictionary has both values, add a print() statement to see the final result:
dictionary = {'1': input('Choose: [1]Red [2]Blue'), '2':input('Choose: [1]Green [2]Yellow')} # Print the full dictionary to verify both values are stored print(dictionary)
For example, if you enter Red for the first prompt and Yellow for the second, the output will be:
{'1': 'Red', '2': 'Yellow'}
So rest assured, using input() for dictionary values is totally supported—you just need to make sure you complete all input steps and check the entire dictionary to see all results.
内容的提问来源于stack exchange,提问作者bajotupie

