Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #78685

Issue in printing top 20 dictionary items by dictionary value

From Shiva <shivaji_tn@yahoo.com>
Subject Issue in printing top 20 dictionary items by dictionary value
Date 2014-10-04 09:11 +0000
Newsgroups comp.lang.python
Message-ID <mailman.14596.1412413918.18130.python-list@python.org> (permalink)

Show all headers | View raw


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]))??
           

Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread


Thread

Issue in printing top 20 dictionary items by dictionary value Shiva <shivaji_tn@yahoo.com> - 2014-10-04 09:11 +0000
  Re: Issue in printing top 20 dictionary items by dictionary value Alexander Blinne <news@blinne.net> - 2014-10-04 12:28 +0200
    Re: Issue in printing top 20 dictionary items by dictionary value Shiva <shivaji_tn@yahoo.com> - 2014-10-04 17:36 +0000
      Re: Issue in printing top 20 dictionary items by dictionary value Larry Hudson <orgnut@yahoo.com> - 2014-10-04 14:44 -0700
        Re: Issue in printing top 20 dictionary items by dictionary value Shiva <shivaji_tn@yahoo.com> - 2014-10-05 06:58 +0000
    Re: Issue in printing top 20 dictionary items by dictionary value MRAB <python@mrabarnett.plus.com> - 2014-10-04 20:40 +0100
  Re: Issue in printing top 20 dictionary items by dictionary value Denis McMahon <denismfmcmahon@gmail.com> - 2014-10-05 01:11 +0000
    Re: Issue in printing top 20 dictionary items by dictionary value MRAB <python@mrabarnett.plus.com> - 2014-10-05 02:41 +0100

csiph-web