Counting/Print Unique Words in Directory up to x instances
<p>I am attempting to take all unique words in tale4653, count their instances, and then read off the top 100 mentioned unique words. </p>

<p>My struggle is sorting the directory so that I can print both the unique word and its' respected instances. </p>

<h2>My code thus far:</h2>

<pre><code>import string 

fhand = open('tale4653.txt')

counts = dict()

for line in fhand:

    line = line.translate(None, string.punctuation)

    line = line.lower()

    words = line.split()

    for word in words:

        if word not in counts:

            counts[word] = 1

        else:

            counts[word] += 1

fhand.close()

rangedValue = sorted(counts.values(), reverse=True)

i =0 

while i&lt;100:

    print rangedValue[i]

    i=i+1
</code></pre>

<p>Thank you community, </p>

<p>DorElias is correct in the initial problem: you need to use <code>count.items()</code> with <code>key=lambda x: x[1]</code> or <code>key=operator.itemgetter(1)</code>, latter of which would be faster.</p>

<hr>

<p>However, I'd like to show how I'd do it, completely avoiding <code>sorted</code> in your code. <code>collections.Counter</code> is an optimal data structure for this code. I also prefer the logic of reading words in a file be wrapped in a generator</p>

<pre><code>import string 
from collections import Counter

def read_words(filename):
    with open(filename) as fhand:
        for line in fhand:
            line = line.translate(None, string.punctuation)
            line = line.lower()
            words = line.split()
            for word in words: # in Python 3 one can use `yield from words`
                yield word        

counts = Counter(read_words('tale4653.txt'))
for word, count in counts.most_common(100):
    print('{}: {}'.format(word, count))
</code></pre>

python sorting while-loop directory