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

如何在Python字典中使用input()函数获取的用户输入作为值?

Can I use input() results as Python dictionary values?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:44:55