Python:简单字典引用问题

标签 python dictionary

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

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/

相关文章:

python - Maya Python 在渲染设置中更改当前渲染器

python - 引用python中文件的下载

python - Django 更改数据库中错误的列名

flash - 有趣的 AS3 哈希情况。它真的像文档所说的那样使用严格的平等吗?

python - 从 dict 创建数据框 pandas,其中值是元组列表,每个列名称都是唯一的

javascript - 交换字典将类型更改为整数

python - 用于匹配 Python 列表中特定模式的正则表达式

Python - 如果仅指定条件(域),则添加条件?

java - 如何在ViewText上添加换行符?

Python按索引迭代字典