开发者

Python: Simple Dictionary referencing Problem

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


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'


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜