tags:

views:

69

answers:

4

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 attribute:")
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
+2  A: 

Just use the indexing operator:

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

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.

Jim Brissom
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.

digitaldreamer
@digitaldreamer: Hey--give me my gravatar back!
Pete
A: 

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
froadie
Dictionaries iterate over their own keys -- `for i in python:` is sufficient and idiomatic.
Daenyth