# 如何根据字典“键”或“键值”进行不同顺序的排序?dic = {'c': 1, 'a': 3, 'b': 2}# 按键升序排序key_asc = sorted(dic.items(), key=lambda item:item[0], reverse=False)print(key_asc)# 结果:[('a', 3), ('b', 2), ('c', 1)]# 按键降序排序key_des = sorted(dic.items(), key=lambda item:item[0], reverse=True)print(key_des)# 结果:[('c', 1), ('b', 2), ('a', 3)]# 按键值升序排序value_asc = sorted(dic.items(), key=lambda item:item[1], reverse=False)print(value_asc)# 结果:[('c', 1), ('b', 2), ('a', 3)]# 按键值降序排序value_des = sorted(dic.items(), key=lambda item:item[1], reverse=True)print(value_des)# 结果:[('a', 3), ('b', 2), ('c', 1)]
来源:https://www.cnblogs.com/shnuxiaoan/p/11452288.html