dit = {1:’a’, -1:’b’, 2:’c’, -2:’d’}
直接使用sorted方法, 只能根据key进行排序
sorted(dit)
Out[6]: [-2, -1, 1, 2]
如果需要根据value排序,可以
sorted(dit.items(),key = lambda x:x[1],reverse = True)
Out[7]: [(-2, ‘d’), (2, ‘c’), (-1, ‘b’), (1, ‘a’)]
本文介绍如何使用Python内置函数sorted()对字典进行排序,包括按键(key)排序及按值(value)排序的方法,并展示了具体操作步骤。
dit = {1:’a’, -1:’b’, 2:’c’, -2:’d’}
直接使用sorted方法, 只能根据key进行排序
sorted(dit)
Out[6]: [-2, -1, 1, 2]
如果需要根据value排序,可以
sorted(dit.items(),key = lambda x:x[1],reverse = True)
Out[7]: [(-2, ‘d’), (2, ‘c’), (-1, ‘b’), (1, ‘a’)]
8617
2344
2574

被折叠的 条评论
为什么被折叠?
