简体   繁体   中英

Python. KeyError after checking that key exist

I have a KeyError message when I try to get a value from dictionary by key. Before get a value by key I check that key is exist. Here is my code:


def getTweetSentiment(tweet_text):
    print sentiment_words #{u'limited': -1, u'cut': 2, ...}
    sentiment = 0
    words = extractWordsFromTweet(tweet_text)
    for word in words:
        test = word.lower() #test is unicode
        if test in sentiment_words.keys(): #Here I check that key is in a list of keys.
            temp = sentiments_words[test]  #!And here throws the KeyError exception
            sentiment = sentiment + temp
    return sentiment

Any ideas why it happens?

The first line shows sentiment_words and the other shows sentiments_words (note the s after sentiment

sentiment_words
sentiments_words

Note that the better solution might be this:

word = sentiment_words.get(test)
if word is not None:  # the `is not None` part is only required if '' could occur as a word
    sentiment += word

Or the simpler version for this case (as Chepner suggested):

sentiment += sentiment_words.get(test, 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM