compare dictionaries

MRAB python at mrabarnett.plus.com
Tue Sep 7 19:17:26 EDT 2010


On 07/09/2010 22:36, Baba wrote:
> On 7 sep, 22:37, MRAB<pyt... at mrabarnett.plus.com>  wrote:
>> On 07/09/2010 21:06, Paul Rubin wrote:
>>
>>> Baba<raoul... at gmail.com>    writes:
>>>> word= 'even'
>>>> dict2 = {'i': 1, 'n': 1, 'e': 1, 'l': 2, 'v': 2}
>>
>>>> i want to know if word is entirely composed of letters in dict2
>>
>>> set(word)<= set(dict2.keys())
>>
>> Do the numbers in dict2 represent the maximum number of times that the
>> letter can be used?
>>
>> If yes, then build a similar dict for the word with the number of times
>> that each letter occurs in the word and then check for every pair in
>> the dict whether the key (ie, letter) occurs in dict2 and that the
>> value (number of occurrences) isn't too many.
>
> Hi MRAB
>
> Thanks for the hint. In my case i need to do the opposite: the number
> of times that each letter ocurs in the word needs to be smaller or
> equal to the number of times it apears in dict2. That way i am
> guaranteed that word is entirely made up of elements of dict2.
>
> Your hint pointed me in the right direction.
>
>          for k in word.keys():
>              if k not in hand:
>                  return False
>              elif k in hand:
>                if word[k]>  hand[k]:
>                    return False
>          return True
>
If the first condition is True then the second will be False, so
there's no need to check it:

          for k in word.keys():
              if k not in hand:
                  return False
              else:
                  if word[k] > hand[k]:
                      return False
          return True

This can be shortened still further.



More information about the Python-list mailing list