On Tue, Jul 6, 2010 at 8:08 PM, Ken G. <beach...@insightbb.com> wrote:
> Is there a way to sort a dictionary? > > Assuming I have a dictionary set containing the following: > > {'02': 1, '03': 1, '12': 1, '15': 2, '14': 2, '04': 3, '05': 1, '19': 1, > '32': 1, '28': 1, '27': 1, '17': 2, '25': 1} > > and using the following code: > > print ('Printing the result of numbers that are repeated:') > print > for x, y in counted.items(): > if y > 1: > print "Number %s was found %s times." % (x,y) > # else: > # print "Number %s was found %s times." % (x,y) > print > > and the result are: > > Printing the result of numbers that are repeated: > > Number 15 was found 2 times. > Number 14 was found 2 times. > Number 04 was found 3 times. > Number 17 was found 2 times. > > and the question is: > > How do I sort the dictionary so the numbers listed (15, 14, 04, 17) are > listed in sorted ascending order such as: > > Number 04 was found 3 times. > Number 14 was found 2 times. > Number 15 was found 2 times. > Number 17 was found 2 times. > >>> d = {'02': 1, '03': 1, '12': 1, '15': 2, '14': 2, '04': 3, '05': 1, '19': 1, '32': 1, '28': 1, '27': 1, '17': 2, '25': 1} >>> import operator >>> sorted(d.items(), key=operator.itemgetter(1), reverse = True) [('04', 3), ('17', 2), ('15', 2), ('14', 2), ('25', 1), ('27', 1), ('02', 1), ('03', 1), ('12', 1), ('05', 1), ('19', 1), ('32', 1), ('28', 1)] ~l0nwlf
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor