I am trying to sort the output of a dictionary by the third column, or more specifically the count of values that appear in the example results. For context, the original answer provide was here: https://stackoverflow.com/a/23199901/666891. I was unable to derive an answer from https://stackoverflow.com/a/73050/666891 or https://stackoverflow.com/a/613218/666891 therefore am asking here.
The original out put is produced from:
for k in ret.keys():
print '%s %d' % (k,ret[k])
Which results in:
google com 1132
akamaiedge net 378
bing com 381
microsoft com 197
And tried:
x = ret.keys()
sorted(x,key=operator.itemgetter(3))
for k in x:
print '%s %d' % (k,ret[k])
which results in:
google com 1132
akamaiedge net 378
bing com 381
microsoft com 197
And lastly tried:
for k in sorted(ret.keys(),key=operator.itemgetter(3),reverse=True):
print '%s %d' % (k,ret[k])
Which resulted in a similar output to the first:
microsoft com 197
akamaiedge net 378
google com 1132
bing com 381
Additionally, the value of ret.keys()
is:
['google com', 'akamaiedge net', 'bing com', 'microsoft com']
Solution for my specific scenario is:
for k in sorted(ret.keys(), key=lambda k:ret[k], reverse=True):
print "{:15} - {}".format(k, ret[k])