FT | 14 May 02:10

Sorting Dictionary Keys


Jim,

OK, use the example below for sorting dictionary keys and placing them in a
list. Note that an error will happen if the format on the print statement
does not correspond to the type of sort.

#THIS SORTS A DICTIONARY BY USING SET THEORY AND DIC ITEMS!
import random
dic = {}
print "Randomizing!"
for i in range(20):
    dic[ random.randrange(100)] = random.randrange(100, 1000)
print "Dic:"
j=0
list=[]
for k,i in dic.items():
    print "K=%d I=%d" % (k,i)
    list.append("K=%d I=%d" % (k,i))
    j+=1

j=0
print "Sorted Dic By Set:"
print "Num: Old,  Sorted"
for k in sorted(set(dic)):
    print "(%d) %s | K=%d I=%d" % (j+1, list[j], k,dic[k])
    j+=1

j=0
print "Sorted Dic By Items:"
(Continue reading)


Gmane