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.