Python字典排序

# -*- coding:UTF-8 -*-

def dict_sort():
    # 按照value的值从大到小的顺序进行排序
    dic = {'a': 31, 'bc': 5, 'c': 3, 'asd': 4, 'aa': 74, 'd': 0}
    dict = sorted(dic.items(), key=lambda d: d[1], reverse=True)  # 默认是从小到大
    print 'dict=', dict

    # 按照key的字母顺序排序
    dictt = sorted(dic.items(), key=lambda d: d[0])
    print 'dictt=', dictt


if __name__ == '__main__':
    dict_sort()

Output:

dict= [('aa', 74), ('a', 31), ('bc', 5), ('asd', 4), ('c', 3), ('d', 0)]
dictt= [('a', 31), ('aa', 74), ('asd', 4), ('bc', 5), ('c', 3), ('d', 0)]
    原文作者:排序算法
    原文地址: https://blog.csdn.net/kevinelstri/article/details/52832524
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞