python 给字典dict对象做排序

lanjianhua / 2024-10-23 / 原文

test_dict = {
    "a": 21,
    "c": 3,
    "g": 56,
    "b": 34,
    "j": 12,
}
sorted_items = sorted(test_dict.items(), key=lambda item: item[1], reverse=True)  # reverse: true 递减排序,false 递增排序

print(sorted_items) # [('g', 56), ('b', 34), ('a', 21), ('j', 12), ('c', 3)]