python - 将字典与列表匹配(Python)

标签 python dictionary

我有一本带有类别的单词词典。如果单词与列表中的单词匹配,我想输出类别。这就是我的代码目前的样子:

dictionary = {
    "object" : 'hat',
    "animal" : 'cat',
    "human" : 'steve'
}

list_of_things = ["steve", "tom", "cat"]

for categories,things in dictionary.iteritems():
    for stuff in list_of_things:

        if stuff in things:
            print categories
        if stuff not in things:
            print "dump as usual"

当前输出如下所示:

dump as usual
dump as usual
dump as usual
human
dump as usual
dump as usual
dump as usual
dump as usual
animal

但我希望输出如下所示:

human
dump as usual 
animal

我不希望我的列表打印它在字典中迭代的所有内容。我只希望它打印匹配的术语。我该怎么做?

最佳答案

首先,你的字典结构很差;它的键和值似乎交换了。通过使用类别作为键,每个类别只能有一个对象,这可能不是您想要的。这也意味着您必须阅读字典中的每个条目才能查找某个项目,这通常是一个坏兆头。解决这个问题的方法很简单:将项目放在冒号的左侧,将类别放在右侧。然后,您可以使用“in”运算符轻松搜索字典。

就您直接提出的问题而言,您应该首先循环遍历 list_of_things,根据字​​典检查每个内容,然后打印结果。这将打印列表中每个项目的一件事。

dictionary = {
    'hat' : 'object',
    'cat' : 'animal',
    'steve' : 'human'
}

list_of_things = ['steve', 'tom', 'cat']

for thing in list_of_things:
    if thing in dictionary:
        print dictionary[thing]
    else:
        print "dump as usual"

输出:

human
dump as usual
animal

关于python - 将字典与列表匹配(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38833527/

相关文章:

python - 环境变量

ios - 在 Swift 中对字典使用过滤器

python - 将一个字典的键替换为另一个字典的值以创建一个新字典

python - 将字典的字典转换为 Pandas 中的数据框

python - 在 Python 字典中搜索匹配键

python 检查 json.dumps 是否可行

python - Matplotlib:手动向axes.prop_cycle()中的默认颜色添加更多颜色?

python - 在 python 日志文件中包含当前日期

python - 了解创建守护进程的Python代码

c++ - SFML 2.0 从 map 文件加载