Python里怎麼按dict value來排序? | how to sort by value in python dict

簡單來說就是先生成 value => key 的tuples,然後call sorted

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
sorted(
[(my_map.get(k), k) for k in my_map],
reverse=True
)
sorted( [(my_map.get(k), k) for k in my_map], reverse=True )
sorted(
    [(my_map.get(k), k) for k in my_map],
    reverse=True
)

另一種方法是call dict的items來產生dict_items,這個大概就像list of tuples with key and value。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
d = {'a':1, 'b':2, 'c':3, 'd':64}
d.items()
d = {'a':1, 'b':2, 'c':3, 'd':64} d.items()
d = {'a':1, 'b':2, 'c':3, 'd':64}
d.items()

輸出

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 64)])
dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 64)])
dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 64)])

所以排序可以用

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
sorted([(v, k) for k,v in d.items()], reverse=True)
sorted([(v, k) for k,v in d.items()], reverse=True)
sorted([(v, k) for k,v in d.items()], reverse=True)

輸出

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[(64, 'd'), (3, 'c'), (2, 'b'), (1, 'a')]
[(64, 'd'), (3, 'c'), (2, 'b'), (1, 'a')]
[(64, 'd'), (3, 'c'), (2, 'b'), (1, 'a')]

本文鏈接

Leave a Comment

Your email address will not be published.