我有一个我无法解决的简单问题。我有一本字典:
aa = {'ALA':'A'}
test = 'ALA'
我在编写代码时遇到问题,其中从测试中获取并在字典 aa 中引用并打印“A”。
我假设我必须使用 for 循环?像...
for i in test:
if i in aa:
print i
我了解如何引用字典:
aa['ALA']
它从 i 中获取值并使用它来引用我遇到问题的 aa。
谢谢
詹姆斯
最佳答案
不确定您要做什么,但也许您的意思是:
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.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'
关于Python:简单字典引用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2392920/