Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>(1) You don't actually define <code>word_count</code> in <code>dict_creator</code>. I was expecting to see</p> <pre><code>word_count = {} </code></pre> <p>at the start. This means that whatever <code>word_count</code> it's changing is defined elsewhere and global, so whenever you call <code>dict_creator</code> it'll add to the same <code>word_count</code> dictionary, increasing the values. You only ever have one <code>word_count</code>, at least from the code you've shown.</p> <p>(2) As for the KeyError:</p> <pre><code> for word in sorted(word_count.iteritems(), key=operator.itemgetter(1), reverse=True): #create sorted list of tuples using operator module functions sorted in an inverse manner a = word b = word_count[word] </code></pre> <p><code>iteritems()</code> returns the tuples, so <code>word</code> is already something like <code>('dict_creator', 1)</code>. You can simply print it as it is. Calling <code>word_count[word]</code> tries to use the tuple of <code>(key, value)</code> as the key. IOW, even though you've called the variable word, it's really <code>word_and_count</code>, with <code>word, count = word_and_count</code>.</p> <p>(3) In this part:</p> <pre><code> return word_count #return word_count dictionary word_count.close() </code></pre> <p>I think you mean <code>input_file.close()</code>, but there's no point in closing the file "after" you return, because that line won't be executed. Another option is to use the <code>with</code> idiom:</p> <pre><code>with open(filename) as input_file: code_goes_here = True return word_count </code></pre> <p>here the file will automatically be closed.</p> <p>After making the above changes, your code seems to work for me.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload