将字典与列表匹配(Python)

时间:2016-08-08 15:47:26

标签: 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

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

4 个答案:

答案 0 :(得分:1)

您可以在内部for循环中使用布尔值,该布局从False(未找到类别)更改为True(找到类别),然后仅在处打印categories for循环if boolean = False:

的结束
isMatchFound = False
for categories, things in dictionary.iteritems():
    isMatchFound = False
    for stuff in list_of_things:
        if stuff in things:
            isMatchFound = True
            print stuff
    if isMatchFound == False:
        print("dump as usual")

答案 1 :(得分:1)

根据您的实际数据的大小,您可以执行

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

list_of_things = ["steve", "tom", "cat"]
thingset=set(list_of_things) # just for speedup

for category,thing in category_thing.iteritems():

        if thing in thingset:
            print category
        else:
            print "dump as usual"

或者如果你的映射真的像你的例子那样简单,你可以做到

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

thing_category=dict((t,c) for c,t in category_thing.items()) # reverse the dict - if you have duplicate values (things), you should not do this

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

for stuff in list_of_things:
     msg=thing_category.get(stuff,"dump as usual")
     print msg

答案 2 :(得分:1)

首先,你的词典结构很差;似乎交换了键和值。通过将类别用作键,每个类别只能有一个对象,这可能不是您想要的。这也意味着您必须阅读字典中的每个条目才能查找项目,这通常是一个不好的标志。对此的修复很简单:将项目放在冒号的左侧,将类别放在右侧。然后,您可以使用“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

答案 3 :(得分:0)

由于输出中只需要3行,因此应重新排序for循环。

for stuff in list_of_things:
  print_val = None
  for categories,things in dictionary.iteritems():
    if stuff in things:
      print_val=categories
  if print_val is None:
    print_val="dump as usual"
  print print_val