4

I am pretty new to python, but I know the basic commands. I am trying to create a for loop which, when given a list of sentences, adds a key for the length of each sentence. The value of each key would be the frequency of that sentence length in the list, so that the format would look something like this:

dictionary = {length1:frequency, length2:frequency, etc.}

I can't seem to find any previously answered questions that deal with this specifically - creating keys using basic functions, then changing the key's value by the frequency of that result. Here is the code I have:

dictionary = {}
for i in sentences: 
    dictionary[len(i.split())] += 1

When I try to run the code, I get this message:

Traceback (most recent call last):
  File "<pyshell#11>", line 2, in <module>
    dictionary[len(i.split())] += 1
KeyError: 27

Any help fixing my code and an explanation of where I went wrong would be so appreciated!

boop
  • 59
  • 5
  • What Python version are you running? I've never seen this error before. – Rushy Panchal Sep 05 '16 at 04:30
  • 4
    Possible duplicate of [SyntaxError: multiple statements found while compiling a single statement](http://stackoverflow.com/questions/21226808/syntaxerror-multiple-statements-found-while-compiling-a-single-statement) – Rushy Panchal Sep 05 '16 at 04:31
  • Can't reproduce the error, you should get a `KeyError` in stead. – Ahsanul Haque Sep 05 '16 at 04:31
  • I'm using Python 3.5, doing all my editing just using IDLE – boop Sep 05 '16 at 04:31
  • @boop, see the second comment added then. It has the answer to your question. – Ahsanul Haque Sep 05 '16 at 04:33
  • After running the line creating the blank dictionary first, then running the for loop separately, I got KeyError 27, I am updating the question to reflect this – boop Sep 05 '16 at 04:38
  • @boop Yes. Because you don't have an initialized value in your dictionary. You are trying to increment by 1 without having initialized a value. You should use `defaultdict` from `collections`: [documentation](https://docs.python.org/3/library/collections.html#collections.defaultdict). `dictionary = defaultdict(int)`. Changing that line and copy pasting your code, everything works for me. – idjaw Sep 05 '16 at 04:40
  • @idjaw Thank you! – boop Sep 05 '16 at 04:43

1 Answers1

2

I think this will solve your problem, in Python 3:

sentences ='Hi my name is xyz'
words = sentences.split()
dictionary ={}
for i in words: 
    if len(i) in dictionary:
        dictionary[len(i)]+=1
    else:
        dictionary[len(i)] = 1
print(dictionary)

Output:

{2: 3, 3: 1, 4: 1}

In dictionary, first you have to assign some value to key then only you can use that value for further calculations Or else there is alternative use defaultdict to assign default value to each key.

Hope this helps.

Kalpesh Dusane
  • 1,477
  • 3
  • 20
  • 27