How to sort a dict by values and return a list of formatted strings?
I've got a dict:开发者_如何学C
text_to_count = { "text1": 1, "text2":0, "text3":2}
I'd like to create a list of formatted strings by sorting this dict's values (in descending order).
I.e., I like following list:
result = ["2 - text3", "1 - text1", "0 - text2"]
Any ideas?
Edit:
While waiting for responses, I kept hacking at it and came up with:
result = map(lambda x: "{!s} - {!s}".format(x[1], x[0]),
sorted(text_to_count.iteritems(),
key = lambda(k, v): (v, k), reverse=True ))
Tho I'm still interested in seeing what other solutions there are, possibly one better.
['%d - %s' % (v, k) for (k, v) in sorted(text_to_count.iteritems(),
key=operator.itemgetter(1), reverse=True)]
How's this?
result = ['{1} - {0}'.format(*pair) for pair in sorted(text_to_count.iteritems(), key = lambda (_,v): v, reverse = True)]
And one more, codegolf style:
>>> ['%s - %s'%(t[x],x) for x in sorted(t,key=t.get)[::-1]]
['2 - text3', '1 - text1', '0 - text2']
PS. to illustrate a point brought by Ignacio Vazquez-Abrams comment, note how the sorts results can vary if there are value repeats:
>>> t={'txt1':1, 'txt2':0, 'txt3':1}
>>> ['%s - %s'%(t[x],x) for x in sorted(t,key=t.get)[::-1]]
['1 - txt3', '1 - txt1', '0 - txt2']
>>> ['%s - %s'%(t[x],x) for x in sorted(t,key=t.get,reverse=True)]
['1 - txt1', '1 - txt3', '0 - txt2']
精彩评论