compare dictionaries

Peter Otten __peter__ at web.de
Tue Sep 7 17:08:49 EDT 2010


Baba wrote:

> 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

Just compare the two dictionaries

dict1 == dict2

Or, if you want to allow dict2 to contain higher but not lower values

all(v <= dict2.get(k, 0) for k, v in dict1.iteritems())

Peter



More information about the Python-list mailing list