Python:简单的字典引用问题

2024-03-28 12:46:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我在编写代码时遇到了麻烦,在这里从test中获取并引用字典aa,并且打印了'A'。在

我想我必须使用for循环?像是。。。在

^{pr2}$

我理解如何引用字典:

aa['ALA'] 

它从i取值并用它来引用我遇到问题的aa。在

谢谢

詹姆斯


Tags: 代码testfor字典aaalapr2
2条回答

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

你是说这个吗?在

print aa[test]

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

我不太明白为什么要对字符串变量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

请注意,您可以从字典中生成三种不同类型的迭代器:

^{pr2}$

相关问题 更多 >