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>you loose the word (the key in your dictionary) when you do <code>counts.values()</code>)</p>

<p>you can do this instead</p>

<pre><code>rangedValue = sorted(counts.items(), reverse=True, key=lambda x: x[1])
for word, count in rangedValue:
    print word + ': ' + str(rangedValue)
</code></pre>

<p>when you do counts.items() it will return a list of tuples of key and value like this:</p>

<pre><code>[('the', 1), ('end', 2)]
</code></pre>

<p>and when we sort it we tell it to take the second value as the "key" to sort with</p>

python sorting while-loop directory