python - 如何在python中使用变量作为字典的键

标签 python dictionary

嗨,我是 python 的新手,所以如果我问的是非常愚蠢的问题,请原谅。所以,我有一个名为 array 的字典,它有一些值,现在我想将键作为变量输入并使用它来打印分配给该键的值。

array = {'color':'blue' , 'size':'small'}
print array ['color']

这工作得很好,输出值蓝色。但如果我尝试这样做,它就不起作用。

array = {'color':'blue' , 'size':'small'}
var = input ('input a key') #input would be " color " or " size "
print array[var]

我认为有一个非常简单的解决方案。感谢您提前提供帮助:)

最佳答案

您的输入包含前导和尾随空格。例如,'color''color' 不同。您的字典没有关键字 ' color '。您可以像这样从输入字符串中去除空格:

>>> mydict = {'color':'blue' , 'size':'small'}
>>> var = input().strip()
' color '
>>> mydict[var]
'blue'

顺便说一下,您的array 是一个Python 字典,称它为array 有点令人困惑。

关于python - 如何在python中使用变量作为字典的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34274505/

相关文章:

python - Flask 和 WTForms - 如何让 wtforms 刷新选择的数据

python - 当键是 Python 字典中的元组时

python - 计算字符串中每个字母的频率

ios - 如何快速创建和添加值到字典

python - 如何在 Python 中使用 pickle 创建持久类

python - 奇怪的打印语法错误

python - 在 AWS EC2 上部署 django 应用程序时无法在端口 80 上运行 gunicorn

python - 在许多单独的线程中测试 Django 应用程序

python - 初学者 : How to configure my python interpreter to use the correct path to get the right version of python?

python - 选择组合框值后获取字典的值