【问题标题】:Python: Simple Dictionary referencing ProblemPython:简单的字典引用问题
【发布时间】:2010-03-06 15:12:24
【问题描述】:

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

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

我在编写代码时遇到问题,该代码从 test 中获取并在字典 aa 中引用并打印“A”。

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

for i in test:
    if i in aa:
        print i

我明白如何引用字典:

aa['ALA'] 

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

谢谢

詹姆斯

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    不确定您要做什么,但也许您的意思是:

    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'
    

    【讨论】:

      【解决方案2】:

      我在编写代码时遇到问题,该代码从 test 中获取并在字典 aa 中引用并打印“A”。

      你是这个意思吗?

      print aa[test]
      

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

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

      【讨论】:

      • 我打算在更大的字典上使用它,如果取多个值,引用到字典中并打印出来。我不打算对角色进行互动,现在我明白了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-30
      相关资源
      最近更新 更多