How to display dictionary by their values, descending?
I have a dictionary as follows:
{'aapl': 4.0,
'abandon': 4.0,
'absenc': 3.0,
'accept': 1.0,
'access': 3.0,
'accessori': 4.0,
'accord': 3.0,
'achiev': 1.0,
'acquir': 1.5,
'acquisit': 2.3333333333333335,
'across': 5.0,
'activ': 2.0,
'ad': 2.2692307692307692,
'add': 2.5,
'addit': 2.8333333333333335,
}
开发者_高级运维
How do I display them by their score (descending) ?
I heard that there's a way to do it via tuples or something?
>>> D={'aapl': 4.0,
... 'abandon': 4.0,
... 'absenc': 3.0,
... 'accept': 1.0,
... 'access': 3.0,
... 'accessori': 4.0,
... 'accord': 3.0,
... 'achiev': 1.0,
... 'acquir': 1.5,
... 'acquisit': 2.3333333333333335,
... 'across': 5.0,
... 'activ': 2.0,
... 'ad': 2.2692307692307692,
... 'add': 2.5,
... 'addit': 2.8333333333333335,
... }
>>> sorted(D, key=D.get, reverse=True)
['across', 'aapl', 'accessori', 'abandon', 'accord', 'access', 'absenc', 'addit', 'add', 'acquisit', 'ad', 'activ', 'acquir', 'accept', 'achiev']
>>>
If you want the values too,
>>> from operator import itemgetter
>>> sorted(D.items(), key=itemgetter(1), reverse=True)
[('across', 5.0), ('aapl', 4.0), ('accessori', 4.0), ('abandon', 4.0), ('accord', 3.0), ('access', 3.0), ('absenc', 3.0), ('addit', 2.8333333333333335), ('add', 2.5), ('acquisit', 2.3333333333333335), ('ad', 2.2692307692307692), ('activ', 2.0), ('acquir', 1.5), ('accept', 1.0), ('achiev', 1.0)]
It's the fastest way I know:
d = { ... } # your dictionary
for name, score in sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True):
print score, name
mydict = {'aapl': 4.0,
'abandon': 4.0,
'absenc': 3.0,
'accept': 1.0,
'access': 3.0,
'accessori': 4.0,
'accord': 3.0,
'achiev': 1.0,
'acquir': 1.5,
'acquisit': 2.3333333333333335,
'across': 5.0,
'activ': 2.0,
'ad': 2.2692307692307692,
'add': 2.5,
'addit': 2.8333333333333335,
}
sorted([(y,x) for x,y in mydict.items()], reverse=True)
This produces:
[(5.0, 'across'), (4.0, 'accessori'), (4.0, 'abandon'), (4.0, 'aapl'), (3.0, 'accord'), (3.0, 'access'), (3.0, 'absenc'), (2.8333333333333335, 'addit'), (2.5, 'add'), (2.3333333333333335, 'acquisit'), (2.269230769230769, 'ad'), (2.0, 'activ'), (1.5, 'acquir'), (1.0, 'achiev'), (1.0, 'accept')]
This has the side effect of sorting by the key for values that are the same (e.g., for value == 3.0, 'absenc' < 'access' < 'accord')
by_score = yourdict.items()
by_score.sort(key=operator.itemgetter(1), reversed=True)
精彩评论