views:

50

answers:

2

I have a simple problem that i cannot solve. I have a dictionary:

aa = {'ALA':'A'}
test = 'ALA'

I'm have trouble writing code where that value from test is taken and referenced in the dictionary aa and 'A' is printed.

I'm assuming i would have to use a for loop? something like...

for i in test:
    if i in aa:
        print i

I understrand how to referenced a dictionary:

aa['ALA'] 

Its taking the value from i and using it to reference aa i am having trouble with.

Thanks

James

+2  A: 

I'm have trouble writing code where that value from test is taken and referenced in the dictionary aa and 'A' is printed.

Do you mean this?

print aa[test]

Its taking the value from i and using it to reference aa i am having trouble with.

I don’t exactly understand why you’re iterating over the characters in the string variable test. Is this really what you want? The rest of your question suggests that it’s not.

Konrad Rudolph
I'm planning on using this on a larger dictionary, were multiple values are taken, referenced into a dictionary and printed.I didnt intend to interate over the character, i understand now that i did.
James
+2  A: 

Not sure what you are trying to do, but perhaps you mean:

aa = {'ALA':'A'}
test = ['ALA']  ### note this is now a list!

for i in test:
    if i in aa:
        print i, aa[i]  #### note i is the key, aa[i] is the value

note that you can make three different kinds of iterators from a dictionary:

aa.iteritems()   # tuples of (key, value)
                 # ('ALA', 'A')
aa.iterkeys()    # keys only -- equivalent to just making an iterator directly from aa
                 # 'ALA'
aa.itervalues()  # items only
                 # 'A'
Andrew Jaffe