Why is this Python program raising an error while updating a dictionary?

The problem given is that I have been given a file with some text. I have to count the number of times all the word occurs.

What I have tried so far:

def print_words(filename):
    input_file = open(filename, 'r')
    words = input_file.read().split()
    result = {}
    for word in words:
        if word in result:
            result.update({word:1})
        else:
            result[word] += 1
    for count in result:
        print(count + ' => ' + str(result[count]))

The error I am getting:

File "wordcount.py", line 50, in print_words
    result[word] += 1
KeyError: 'We'

Any help will be really appreciated.

Upvotes: 2

Views: 296

Answers (3)

jonrsharpe
jonrsharpe

Reputation: 122024

When you iterate through your words:

for word in words:
    if word in result:
        result.update({word:1})
    else:
        result[word] += 1

You add word to result using update only when it is already there (if word in result:). If it is not there, you try to add one to its value anyway, which Python can't do, hence the KeyError.

The minimal fix is either:

  1. Switch the lines inside the if and else blocks around; or
  2. Change to if word not in result.

Alternatively, you can simplify with collections.defaultdict:

from collections import defaultdict

result = defaultdict(int)

for word in words:
    result[word] += 1

Upvotes: 4

Larry Lustig
Larry Lustig

Reputation: 50970

Okay, what's happening is that the variable word contains the "We". You're trying to increment the counter in the dictionary, but Python is telling you that "We" is not (yet) a key in the dictionary.

This indicates that there's an error in your add-to-dictionary logic and, indeed, looking at the program you only add the word to the dictionary if it's already in the dictionary. Replace

 if word in result:

with

 if word not in result:

and you'll be on your way.

Upvotes: 1

anon582847382
anon582847382

Reputation: 20361

At the moment, you are saying that if the item is already in the dictionary, set it to 1. But if it doesn't exist, you try to reassign the value. This is obviously the wrong way round.


To fix this, replace:

if word in result:

with:

if word not in result:

There you go, problem solved.

Upvotes: 1

Related Questions