Match dictionary with list (Python) -


i have dictionary of words categories. want output categories if words match words in list. code looks @ moment:

dictionary = {     "object" : 'hat',     "animal" : 'cat',     "human" : 'steve' }  list_of_things = ["steve", "tom", "cat"]  categories,things in dictionary.iteritems():     stuff in list_of_things:          if stuff in things:             print categories         if stuff not in things:             print "dump usual" 

currently output looks this:

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

but want output this:

human dump usual  animal 

i don't want list print iterates through in dictionary. want print terms match. how this?

first of all, dictionary poorly structured; seems have keys , values swapped. using categories keys, can have 1 object per category, not want. means have read every entry in dictionary in order item, bad sign. fix simple: put item on left of colon, , category on right. can use 'in' operator search dictionary.

as far question directly asking, should looping on list_of_things first, checking each against dictionary, printing result. print 1 thing per item in list.

dictionary = {     'hat' : 'object',     'cat' : 'animal',     'steve' : 'human' }  list_of_things = ['steve', 'tom', 'cat']  thing in list_of_things:     if thing in dictionary:         print dictionary[thing]     else:         print "dump usual" 

this outputs:

human dump usual animal 

Comments