将字典与列表匹配(Python)
我有一本分类词典。如果单词与列表中的单词匹配,我想输出类别。这就是我的代码目前的样子:将字典与列表匹配(Python),python,dictionary,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
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
我不想让我的列表在字典中打印出它迭代的所有内容。我只希望它打印匹配的术语。我该怎么做 您可以在内部
for
循环中使用一个布尔值,该值从False(未找到类别)变为True(找到类别),然后仅在for
循环的末尾打印类别,如果布尔值=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")
根据实际数据与示例的相似程度,您可以这样做
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
因为输出中只需要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
首先,你的字典结构不好;它似乎有它的键和值交换。通过使用类别作为键,每个类别只能有一个对象,这可能不是您想要的。这也意味着你必须阅读字典中的每一个条目才能找到一个条目,这通常是一个坏兆头。解决方法很简单:将项目放在冒号的左侧,将类别放在右侧。然后可以使用“in”操作符轻松搜索字典
至于你直接问的问题,你应该先把问题列表循环一遍,对照字典检查每一个问题,然后打印结果。这将为列表中的每个项目打印一个内容
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
你是想遍历字典,还是仅仅遍历列表?Urr我应该把布尔值放在哪里?很抱歉我是个十足的傻瓜!这将导致从category\u thing
@KrishnachandraSharma中丢失重复值是的,添加了更安全的解决方案如此简单却如此有效!非常感谢你!不客气。Python非常擅长优雅地处理数据集合,因此数据的结构非常重要。