I am running the following code to count how many times a word occured in a text file.
def print_words(filename):
f = open(filename, 'rU')
dict={}
for line in f:
words=line.split()
for word in words:
if dict.get(word):
dict[word]=dict[word]+1
else:
dict[word]=1
ke = sorted(dict.keys())
for k, v in ke: print k, v
The dictionary file should hold each word and its count. I was able to get that working fine. But I failed to sort the
sorted(dict.keys())returns a sorted list of just the keys. Your for loop is incorrectly expecting to find the values in the same list. Try the code below instead: