Akash Chakraborty
Akash Chakraborty

Reputation: 1

How to get rid of key error: " " in a python programming?

The following is a program to count only words in a string of sentence-

def count_letters(text):
  result = {}
  # Go through each letter in the text
  for letter in text.lower():
    # Check if the letter needs to be counted or not
    if letter.isalpha():
        if letter not in result:
          result[letter]=0
    # Add or increment the value in the dictionary
    result[letter]+=1
  return result

Every time I am getting this error-

Error on line 10:
    result[letter]+=1
KeyError: ' '

Can any one tell me what I am doing wrong?

Upvotes: 0

Views: 252

Answers (2)

Akash Chakraborty
Akash Chakraborty

Reputation: 1

I got the answer! Here is the modified code:

    def count_letters(text):
      result = {}
      # Go through each letter in the text
      for letter in text.lower():
        # Check if the letter needs to be counted or not
        if letter.isalpha():
            if letter not in result:
              result[letter]=0
        # Add or increment the value in the dictionary
        if letter in result:
           result[letter]+=1

  return result

Upvotes: 0

AKX
AKX

Reputation: 169338

You're only initializing the result dict for isalpha characters, yet incrementing it for everything:

def count_letters(text):
    result = {}
    for letter in text.lower():
        if letter.isalpha():
            if letter not in result:
                result[letter] = 0
        result[letter] += 1  # <-- this occurs whether or not `isalpha` is true
    return result

The simple fix is

def count_letters(text):
    result = {}
    for letter in text.lower():
        if letter.isalpha():
            if letter not in result:
                result[letter] = 0
            result[letter] += 1
    return result

and we can further improve this by using .get() to initialize the dict key as we go:

def count_letters(text):
    result = {}
    for letter in text.lower():
        if letter.isalpha():
            result[letter] = result.get(letter, 0) + 1
    return result

We can still do better with some library methods; collections.Counters automagically initialize entries to zero and otherwise act like dicts (with some additional methods):

import collections


def count_letters(text):
    result = collections.Counter()
    for letter in text.lower():
        if letter.isalpha():
            result[letter] += 1
    return result

... and finally we can do even better with a list comprehension since Counters can be initialized from sequences:

import collections

def count_letters(text):
    return collections.Counter(
        [
            letter
            for letter in text.lower()
            if letter.isalpha()
        ]
    )

Upvotes: 2

Related Questions