Issue in printing top 20 dictionary items by dictionary value

Shiva shivaji_tn at yahoo.com
Sat Oct 4 05:11:43 EDT 2014


Hi All,

I have written a function that 
-reads a file 
-splits the words and stores it in a dictionary as word(key) and the total
count of word in file (value).

I want to print the words with top 20 occurrences in the file in reverse
order - but can't figure it out. Here is my function:

def print_top(filename):

    #Open a file
    path = '/home/BCA/Documents/LearnPython/ic/'
    fname = path + filename
    print ('filename: ',fname)
    filetext = open(fname)

    #Read the file
    textstorage={}

    #print(type(textstorage))
    readall = filetext.read().lower()
    eachword = set(readall.split())

    #store split words as keys in dictionary
    for w in eachword:
        textstorage[w] = readall.count(w)

    #print top 20 items in dictionary by decending order of val
    # This bit is what I can't figure out.

    for dkey in (textstorage.keys()):
            print(dkey,sorted(textstorage[dkey]))??
           




More information about the Python-list mailing list