compare dictionaries

Baba raoulbia at gmail.com
Tue Sep 7 16:26:10 EDT 2010


On 7 sep, 22:08, Gary Herron <gher... at digipen.edu> wrote:
> 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

ok but how do we address the fact that letter e needs to have the
value 2 in the dictionary if it was to be True? in my example this
condition is not met so the check would return False. Word is not
entirely composed of letters in dict2, one of the letter is not in
dict2 i.e. the 2nd e

So finding a matching key seems to be the easy part, checking if the
number of ocurrences of letter in 'word' == letter.value seems to be
the tricky part




More information about the Python-list mailing list