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/