Python:简单的字典引用问题

Python:简单的字典引用问题,python,dictionary,Python,Dictionary,我有一个我无法解决的简单问题。我有一本字典: aa = {'ALA':'A'} test = 'ALA' aa['ALA'] aa.iteritems() # tuples of (key, value) # ('ALA', 'A') aa.iterkeys() # keys only -- equivalent to just making an iterator directly from aa # 'ALA

我有一个我无法解决的简单问题。我有一本字典:

aa = {'ALA':'A'}
test = 'ALA'
aa['ALA'] 
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'
我在编写代码时遇到困难,因为测试中的值被提取并引用到字典aa中,并且“A”被打印出来

我假设我必须使用for循环?类似于

for i in test:
    if i in aa:
        print i
我了解如何引用词典:

aa = {'ALA':'A'}
test = 'ALA'
aa['ALA'] 
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'
它从我这里获取值,并用它来引用我遇到麻烦的aa

谢谢

詹姆斯

我在编写代码时遇到困难,因为测试中的值被提取并引用到字典aa中,并且“A”被打印出来

你是说这个吗

print aa[test]
它从我这里获取值,并用它来引用我遇到麻烦的aa

我不太明白为什么要迭代字符串变量
test
中的字符。这真的是你想要的吗?你剩下的问题表明它不是

我在编写代码时遇到困难,因为测试中的值被提取并引用到字典aa中,并且“A”被打印出来

你是说这个吗

print aa[test]
它从我这里获取值,并用它来引用我遇到麻烦的aa


我不太明白为什么要迭代字符串变量
test
中的字符。这真的是你想要的吗?你问题的其余部分表明不是这样。

不确定你想做什么,但也许你的意思是:

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
请注意,可以从字典中生成三种不同类型的迭代器:

aa = {'ALA':'A'}
test = 'ALA'
aa['ALA'] 
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'

不确定你想做什么,但也许你的意思是:

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
请注意,可以从字典中生成三种不同类型的迭代器:

aa = {'ALA':'A'}
test = 'ALA'
aa['ALA'] 
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'

我计划在一个更大的字典上使用它,如果取多个值,引用到字典中并打印出来。我不打算在字符上进行交互,我现在明白了。我计划在一个更大的字典上使用它,如果多个值被提取,引用到字典中并打印出来。我不想为这个角色争吵,我现在明白了,我是这么做的。