compare dictionaries

Gary Herron gherron at digipen.edu
Tue Sep 7 16:08:27 EDT 2010


On 09/07/2010 12:46 PM, Baba wrote:
> word= 'even'
> dict2 = {'i': 1, 'n': 1, 'e': 1, 'l': 2, 'v': 2}
>    

Just go through each letter of word checking for its existence in 
dict2.  Return False if one misses, and True if you get through the 
whole word:

def ...():
   for c in word:
     if c not in dict2:
       return False #if any character is not in dict
   return True      # otherwise

If you know of generator expressions, and remember that True and False 
are 1 and 0 respectively, then this works

def ...():
     return sum(c in dict2   for c in word) == len(word)

Gary Herron

-- 
Gary Herron, PhD.
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418




More information about the Python-list mailing list