0
#!/bin/env/python


import sys
import os

if len(sys.argv) == 3:
  #We know the user typed Script then Filename
  file = sys.argv.pop(2)
  num = sys.argv.pop(1)
  #Establish Vars
  f1 = open(file)
  counts = dict()
  #Open the file and create a dictionary

  for line in f1:
    words = line.split()
    for word in words:
      if word not in counts:
        counts[word] = 1
      else:
        counts[word] += 1
  #print counts
  #Iterate through all words and either establish word = 1 or increment
  #counts = sorted(counts, key=words.get)
  print counts


else:
   print('Can you please use this format [script] [number] [file] ')

I need to have this program sort a file in a dictionary by words

I am having an issue, the sorting by the counts does not sort by the count number, I need this to sort to most frequent to least frequent does anyone see the issue. its outputting the numbers chopped off?

Stedy
  • 7,359
  • 14
  • 57
  • 77
user2569803
  • 637
  • 6
  • 11
  • 19
  • 1
    Take a look at the `collections.Counter` class. It has a `most_common` method, which will give you sorted key-value pairs automatically. – Kevin Apr 18 '14 at 20:21
  • illustrative perhaps just to make a list of it i.e [(key,val) for key, val in words.items()] and then just to sort this list. – user1603472 Apr 18 '14 at 20:33
  • @user1603472: what is the point of this list comprehension? what does it add to simply `words.items()`? – njzk2 Apr 18 '14 at 21:03
  • @njzk2 from OPs question I thought it might be easier to follow when you turn the dict into a list that way, but it was a bad thought, you are right. adds nothing. – user1603472 Apr 18 '14 at 22:42

1 Answers1

0

key=counts.get

not

key=words.get

mhb
  • 754
  • 8
  • 20