Looping dictionaries

This is the place for queries that don't fit in any of the other categories.

Looping dictionaries

Postby PyLover » Fri Mar 22, 2013 5:46 pm

I am reading Learn Python the Hard way. I am stuck on ex48. Here's my incomplete solution.

Code: Select all
direction = ['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back']
verb = ['go', 'stop', 'kill', 'eat']
stop  = ['the', 'in', 'of', 'from', 'at', 'in']
noun = ['door', 'bear', 'princess', 'cabinet']
lexicon = {'direction':direction, 'verb':verb, 'stop': stop, 'noun': noun}

def scan(sentence):
   wordlist = sentence.split()
   result = []
   for word in wordlist:
      lower_word = word.lower()
      for key, value in lexicon.items():
         if word in value:
            result.append((key, lower_word))
   print  result
   return result

scan('north door')

Here's my problem. I want to append(('error', lower_word)) if it is not found in the dictionary. How to do this :?
Code: Select all
for key, value in lexicon.items():
         if word in value:
            result.append((key, lower_word))

I know I can use if-else instead of using dictionary. But I don't think it will be good because for more cases I have to write more elifs. Thanks
Posts: 1
Joined: Fri Mar 22, 2013 5:33 pm

Re: Looping dictionaries

Postby ichabod801 » Fri Mar 22, 2013 6:02 pm

Add a break statement when you append the result you did find. Then you can use an else for that for loop (an else on a for loop triggers if the loop exits without a break) that appends the error message.

Another way to do it is to reverse your dictionary. Instead of part_of_speech: list_of_words, have word: part_of_speech. Then you can just check for the word being in your lexicon once, and append the error message if it isn't in the dictionary. This would be a good place for the get method (dict.get(key, default) returns dict[key] if key is in dict, otherwise it returns default).
Due to the reasons discussed here we will be moving to python-forum.io on October 1st, 2016.
This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.
Posts: 688
Joined: Sat Feb 09, 2013 12:54 pm
Location: Outside Washington DC

Return to General Coding Help

Who is online

Users browsing this forum: Bing [Bot] and 12 guests