在Python字典中动态访问键名

2 投票
5 回答
4889 浏览
提问于 2025-04-16 04:11

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

5 个回答

0

你可以用 .keys() 来获取字典里的键。

a = { 'Good' : '0', 'Bad' :'9', 'Lazy' : '7'}
a.keys()
['Good', 'Bad', 'Lazy']

不过要注意的是,字典里的内容是没有顺序的,所以你不能指望它们返回的顺序是固定的。

说到这里,我对你根据例子提出的问题不是很明白。

2

只需要使用索引操作符就可以了:

a = raw_input("which is the final attribute: ")
final_attribute = python[a]
5

试试这个:

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

另外,我不太明白你为什么把你的变量叫做“finalAttribute”,但我觉得有必要提醒你,Python 对字典中键的顺序是没有保证的。

撰写回答