对字典排序

5年以前  |  阅读数:452 次  |  编程语言:Python 
#以上一例子的dic作为排序对象
dic = {0: 1, 2: 2, 4: 4, 6: 1, 7: 1, -6: 1}
dic_after = sorted(dic.items(), key=lambda x:x[1])
# 如果想按key来排序则sorted(dic.items(), key=lambda x:x[0])
# dic_after为一个列表: [(0, 1), (6, 1), (7, 1), (-6, 1), (2, 2), (4, 4)]

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8