I've got a dict:
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With