How to sort a dict by values ​​and return a list of formatted strings?

I have a dict:

text_to_count = { "text1": 1, "text2":0, "text3":2}

I would like to create a list of formatted strings by sorting these dict values ​​(in descending order).

Ie, I like the following list:

result = ["2 - text3", "1 - text1", "0 - text2"]

Any ideas?

Edit:

In anticipation of answers, I continued to crack it and thought up:

result = map(lambda x: "{!s} - {!s}".format(x[1], x[0]), 
                       sorted(text_to_count.iteritems(), 
                       key = lambda(k, v): (v, k), reverse=True ))

I'm still curious to know what other solutions exist, perhaps better.

+3
source share
3 answers

Like this?

result = ['{1} - {0}'.format(*pair) for pair in sorted(text_to_count.iteritems(), key = lambda (_,v): v, reverse = True)]
+1
source
['%d - %s' % (v, k) for (k, v) in sorted(text_to_count.iteritems(),
    key=operator.itemgetter(1), reverse=True)]
+2
source

codegolf:

>>> ['%s - %s'%(t[x],x) for x in sorted(t,key=t.get)[::-1]]
['2 - text3', '1 - text1', '0 - text2']

PS. , -, , , :

>>> 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']

0

Source: https://habr.com/ru/post/1787869/


All Articles