python - 在python字典中动态访问键名

标签 python

Python{ '好':'0','坏':'9','惰性':'7'} 我需要在程序中动态访问键名。例如。

a= raw_input (" which is the final attribute:")
for i in python.items():
    if python.items()[i] == a:
        finalAttribute = python.items()[i]

这给我错误的说法

Traceback (most recent call last):
File "C:/Python27/test1.py", line 11, in <module>
if somedict.items()[i] == a:
TypeError: list indices must be integers, not tuple

最佳答案

尝试:

d = { 'Good' : '0', 'Bad' :'9', 'Lazy' : '7'}
for key in d:
   print "{0} = {1}".format(key, d[key])

此外,我不知道您将变量命名为“finalAttribute”是什么意思,但我觉得有必要提醒您,Python 不保证字典键的顺序。

关于python - 在python字典中动态访问键名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3721387/

相关文章:

python - 使用 Apache 和 Mod_wsgi (windows) 部署现有的 Django 项目

python - 有没有办法在我对 Django 模型进行每次更改后自动重新启动 python 进程?

python - urllib.request : POST data should be bytes, 一个可迭代的字节,或者一个文件对象

python - 给 Pandas 的细胞着色

java - 如何检测xml节点的数量?

python - 使用unittest和mock修补python函数中的变量

python - 我可以让我所有的 python 脚本都缓存字节码吗?在我的主目录的中央目录树下?

python - 如何将xml文件拆分为具有正确文件名的文件?

python - 无法使代数(二次公式)起作用

python - 如何为 Python 获取 "canonical unix shell"