开发者

Accessing key names dynamically in a dictionary in python

Python{ 'Good' : '0', 'Bad' :'9', 'Lazy' : '7'} I need to access the key names dynamically in a program. Eg.

a= raw_input (" which is the final attribu开发者_运维知识库te:")
for i in python.items():
    if python.items()[i] == a:
        finalAttribute = python.items()[i]

This giving me error saying

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


Try:

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

Also, I don't know what you meant when you named your variable "finalAttribute", but I feel obliged to remind you that Python makes no guarantees about the order of dictionary keys.


Just use the indexing operator:

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


You can grab dictionary keys with .keys()

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

One thing to note though is that dictionaries don't have an order, so you shouldn't be depending on the order that things are returned.

With that being said I don't entirely understand your question based on your example.


Firstly, you're misunderstanding how for-each loops work: i is the actual item, not an index.

But besides for that, i in your code is a key-value pair, expressed as a tuple (e.g. ('Good', 0)). You only want the keys. Try:

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


Your code could be written in a simpler form:

a= raw_input (" which is the final attribute:")
for (x),z in python.items():
    if z == a:  
        finalAttribute = x

Note: Your values are in String not Integer

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜