Newbie Question: "How can I sort the dictionary by values() instead of keys()?"
Jae-Min Shin
shinj at pop.nci.nih.gov
Tue May 16 18:35:57 EDT 2000
Hi, I am learning python.
In python book (Quick Python Book), I found that sorting a dictionary
according to keys() can be done by converting it into a list, as shown
below.. But, I don't know how to sort it by values:
import string
dic = {}
fp = open("test.txt", 'r') ### simple text file, for example.
while 1:
line = fp.readline()
if line == '':
fp.close()
break
line = line[:-1] # remove '\n'
words = string.split(line)
for word in words:
dic[word] = dic.get(word, 0) + 1 #0 for new word..
dic_ordered = domain.items() # convert into list for sorting.
dic_ordered.sort() #### sorting by dic.key()
for word in dic_ordered:
print word[0], " was found ", word[1], "times"
print "Total ", len(dic_ordered), " words!!"
JaeM
More information about the Python-list
mailing list