I've been using the solution provided in Sorting_Dictionary to sort a dictionary according to values.I know dictionaries cannot be as such sorted but a list of sorted tupples can be obtained.
Complete code:
import sys
import pprint
def helper(filename):
Word_count={}
f=open(filename)
for line in f:
words=line.split()
for word in words:
word=word.lower()
Word_count.setdefault(word,0)
Word_count[word]+=1
f.close()
return Word_count
def print_words(filename):
Word_count_new=helper(filename)
sorted_count=sorted(Word_count_new.items(),key=Word_count_new.get,reverse=True)
for word in sorted_count:
pprint.pprint(word)
def print_top(filename):
word_list=[]
Word_count=helper(filename)
word_list=[(k,v) for k,v in Word_count.items()]
for i in range(20):
print word_list[i] + '\n'
###
# This basic command line argument parsing code is provided and
# calls the print_words() and print_top() functions which you must define.
def main():
if len(sys.argv) != 3:
print 'usage: ./wordcount.py {--count | --topcount} file'
sys.exit(1)
option = sys.argv[1]
filename = sys.argv[2]
if option == '--count':
print_words(filename)
elif option == '--topcount':
print_top(filename)
else:
print 'unknown option: ' + option
sys.exit(1)
if __name__ == '__main__':
main()
This function produces problem:
def print_words(filename):
Word_count_new=helper(filename)
sorted_count=sorted(Word_count_new.items(),key=Word_count_new.get,reverse=True)
for word in sorted_count:
pprint.pprint(word)
here helper is a method which returns a dictionary which is to be sorted. The dictionary is like this {Dad:1, Mom:2, baby:3}
But this doesn't produce a sorted list of tupples. Instead the output is somewhat random like this
('he', 111)
("hot-tempered,'", 1)
('made', 29)
('wise', 2)
('whether', 11)
('wish', 21)
('scroll', 1)
('eyes;', 1)
('this,', 17)
('signed', 2)
('this.', 1)
How can we explain this behaviour?