如何不使用Python内置sorted函数按字典值排序?
不依赖内置 sorted 函数实现字典按值排序的方案
做字典按值排序的需求时,曾考虑过优先队列的实现思路。最开始依赖内置sorted完成需求的示例代码如下:
import collections nums = [2,3,1,3,2] dic = collections.Counter(nums) sorted_dic = dict(sorted(dic.items(), key=lambda x: x[1]))
通用自定义排序实现
我写了一套可适配数组、字典升/降序排序的通用函数,核心设计如下:
- 排序逻辑为了简化演示,底层选用冒泡排序,后续可直接替换成快速排序、归并排序等任意其他排序算法,不需要修改上层调用逻辑
- 字典场景支持两种排序维度:按字典键排序、按字典值排序
完整实现与配套测试代码如下:
def bubble_sort(arr): # 可替换为任意排序算法,此处为简化演示选用冒泡排序 for i in range(len(arr)-1): for j in range(len(arr)-1-i): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr def my_custom_sort(obj, key=None, reverse=False): if type(obj) == dict: if key == 0: arr = list(map(lambda x: x[0], obj.items())) # 提取字典所有键作为待排序序列 else: dic = {y:x for x,y in obj.items()} # 反转字典键值对,简化按值排序的匹配逻辑 arr = list(map(lambda x: x[0], dic.items())) else: arr = obj sorted_arr = bubble_sort(arr) if reverse: sorted_arr = sorted_arr[::-1] if type(obj) == dict: if key == 0: res = [(key, obj[key]) for key in sorted_arr] return res else: return [(dic[key], key) for key in sorted_arr] return res else: return sorted_arr # 功能测试用例 arr = [4,2,6,7,1] dic = {3:1, 2:4, 1:0, 0:8} print(my_custom_sort(arr)) # 数组升序排序 print(my_custom_sort(arr, reverse=True)) # 数组降序排序 print(my_custom_sort(dic, key=0)) # 字典按键升序排序 print(my_custom_sort(dic, key=1)) # 字典按值升序排序 print(my_custom_sort(dic, key=0, reverse=True)) # 字典按键降序排序 print(my_custom_sort(dic, key=1, reverse=True)) # 字典按值降序排序
运行以上代码的输出结果为:
[1, 2, 4, 6, 7] [7, 6, 4, 2, 1] [(0, 8), (1, 0), (2, 4), (3, 1)] [(1, 0), (3, 1), (2, 4), (0, 8)] [(3, 1), (2, 4), (1, 0), (0, 8)] [(0, 8), (2, 4), (3, 1), (1, 0)]
这套实现可以为需要手写自定义排序逻辑的开发者提供参考,尤其是面试场景下受规则限制无法调用内置排序接口时,可直接复用这套结构完成需求。
内容的提问来源于stack exchange,提问作者Sushil K
相关产品推荐
相关产品推荐

