在python中动态访问字典中的键名
Python{'Good':'0','Bad':'9','Lazy':'7'} 我需要在程序中动态访问密钥名称。例如在python中动态访问字典中的键名,python,Python,Python{'Good':'0','Bad':'9','Lazy':'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)
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
回溯(最近一次呼叫最后一次):
文件“C:/Python27/test1.py”,第11行,在
如果somedict.items()[i]==a:
TypeError:列表索引必须是整数,而不是元组
只需使用索引运算符:
a = raw_input("which is the final attribute: ")
final_attribute = python[a]
尝试:
另外,我不知道您将变量命名为“finalAttribute”是什么意思,但我有义务提醒您,Python不保证字典键的顺序。您可以使用
.keys()获取字典键。
但需要注意的是,字典没有顺序,因此您不应该依赖于返回的顺序
尽管如此,基于您的示例,我并不完全理解您的问题。首先,您误解了每个循环的工作原理:
I
是实际项目,而不是索引
但除此之外,代码中的i
是一个键值对,表示为元组(例如('Good',0)
)。你只想要钥匙。尝试:
a= raw_input (" which is the final attribute:")
for i in python.keys():
if i == a:
finalAttribute = i
您的代码可以用更简单的形式编写:
a= raw_input (" which is the final attribute:")
for (x),z in python.items():
if z == a:
finalAttribute = x
注意:您的值是字符串而不是整数嘿--把我的gravatar还给我!字典在它们自己的键上迭代--
对于python中的i:
就足够了,而且是惯用的。
a= raw_input (" which is the final attribute:")
for i in python.keys():
if i == a:
finalAttribute = i
a= raw_input (" which is the final attribute:")
for (x),z in python.items():
if z == a:
finalAttribute = x