我有一本带有类别的单词词典。如果单词与列表中的单词匹配,我想输出类别。这就是我的代码目前的样子:
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/