Python迭代字典

时间:2015-08-11 16:20:54

标签: python loops dictionary

由于某种原因,我不能在Python中迭代字典。我以前做过但不知何故我不能再做了。虽然我不知道到底是什么,但我觉得我错过了一些明显的东西。我目前正在http://learnpythonthehardway.com/book练习48学习Python。使用Nosetests和给定的测试代码然后我应该在实际脚本中编写相应的代码以使测试工作。这是testfile中的代码:

from nose.tools import *
from ex48 import lexicon


def test_directions():
    assert_equal(lexicon.scan("north"), [('direction', 'north')])
    result = lexicon.scan("north south east")
    assert_equal(result, [('direction', 'north'),
                          ('direction', 'south'),
                          ('direction', 'east')])

所以现在我编写了这段代码来进行测试:

lex = { 'dir':'north', 'dir':'south', 'dir':'east', 'dir':'west', 
        'dir':'down', 'dir':'up', 'dir':'left', 'dir':'right', 
        'verb':'go', 'verb':'stop', 'verb':'kill', 'verb':'eat', 
        'stop':'the', 'stop':'in', 'stop':'of', 'stop':'from', 'stop':'at', 'stop':'it',
        'noun':'door', 'noun':'bear', 'noun':'princess', 'noun':'cabinet'}

def scan(word):
    for k in lex:
        if lex[k] == word:
            return (k, word)
    return None

assert_equal()只检查两个参数是否相同。 我很确定这应该可行,但无论如何我根据Python文档更改了它:

def scan(word):
    for k, v in dict.iteritems():
    if v == word:
        return (k, word)
    return None

两种方式都只是向None投掷,我无法弄清楚原因。

2 个答案:

答案 0 :(得分:0)

构建lex字典的方式是错误的。例如,您首先将北向存储为密钥目录。然后用南方覆盖密钥目录,依此类推。 最后,dir只存储其中一个值。如果您想在一个键中使用多个值,请将它们组合在一个元组中:

"dir" : ("north", "south", "east", "west")

你也需要根据这一变化调整你的其他代码。

答案 1 :(得分:0)

以下内容可以使用,使用每个字典键的可接受单词列表:

lex = { 'dir': ['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right'], 
        'verb': ['go', 'stop', 'kill', 'eat'], 
        'stop': ['the', 'in', 'of', 'from', 'at', 'it'],
        'noun': ['door', 'bear', 'princess', 'cabinet']}

def scan(word):
    for k, v in lex.items():
        if word.lower() in v:
            return (k, word)
    return None

print scan('north')

哪个会打印:

('dir', 'north')