首页 > 解决方案 > 使用用户输入作为字典中的值

问题描述

无论如何使用 input() 作为字典中的值?我努力了:

dictionary = {'1': input('Choose: [1]Red [2]Blue'), '2':input('Choose: [1]Green [2]Yellow')}

但这会返回第一个输入:

'Choose: [1]Red [2]Blue'

标签: python-3.xdictionary

解决方案


看起来很简单。

>>> dictionary = {'1': input('Choose: [1]Red [2]Blue '), '2':input('Choose: 
[1]Green [2]Yellow ')}
Choose: [1]Red [2]Blue 1
Choose: [1]Green [2]Yellow 2
>>> dictionary
{'1': '1', '2': '2'}
>>>

为了代码清晰,您最好将input(...)值分配给变量,并使用变量构造一个新字典。


推荐阅读