user425727
user425727

Reputation:

python comparing dictionaries

level: beginner

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 my approach:

step 1 : convert word to dictionary(dict1)

step2:

for k in dict1.keys(): 
        if k in dict2: 
               if dict1[k] != dict2[k]: 
                   return False 
               return True 

by adding a print statement i can see that this simply ends too early e.g. as soon as the first IF condition is met the loop exits and i won't get a correct answer. i think this is easy but google and python doc didn't return any good hints so i'm trying here.

Thanks Baba

UPDATE

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.

for k in word.keys(): # word has ben converted to key already
    if k not in hand:
        return False
    elif k in hand:
      if word[k] > hand[k]:  
          return False
return True

Upvotes: 1

Views: 993

Answers (5)

John La Rooy
John La Rooy

Reputation: 304137

>>> word = {'e':2, 'v':1, 'n':1}
>>> hand= {'i': 1, 'n': 1, 'e': 1, 'l': 2, 'v': 2}
>>> all(k in hand and v <= hand[k] for k,v in word.items())
False

and now see the true case

>>> hand['e']+=1
>>> all(k in hand and v <= hand[k] for k,v in word.items())
True

Upvotes: 0

Nathan Davis
Nathan Davis

Reputation: 5766

Unless you need it for something else, don't bother constructing dict1. Just do this:

for c in word:
    if c not in dict2:
        return False
return True

Of course, you could also use a set instead of a dict to hold the letters.

Upvotes: 1

Zubin
Zubin

Reputation: 166

You only want to return true after all the checks, so stick it after the loop. Here it is as a straight modification of your code:

for k in dict1.keys(): 
    if k in dict2: 
        if dict1[k] != dict2[k]: 
            return False 
return True 

Upvotes: 0

Bryan Oakley
Bryan Oakley

Reputation: 385900

in your code, just move the "return True" to be outside all the loops. That is, only return true if your loops complete without finding a non-matching value. Whether that's truly what you want for your actual code is hard to say, but moving the "return True" fixes the logic error in the code you posted.

Upvotes: 0

MattH
MattH

Reputation: 38247

>>> word= 'even'
>>> dict2 = {'i': 1, 'n': 1, 'e': 1, 'l': 2, 'v': 2}
>>> set(word).issubset(set(dict2.keys()))
True

Upvotes: 4

Related Questions