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