美文网首页
根据字典中值的大小对字典中的项排序

根据字典中值的大小对字典中的项排序

作者: 慧琴如翌 | 来源:发表于2018-05-04 12:25 被阅读12次

    方法一:

    def dict_sort():
        adict  = {'b':2,'a':1,'d':-3}
        items = adict.items()
        print items  # [('a', 1), ('b', 2), ('d', -3)]
        print sorted(items) # [('a', 1), ('b', 2), ('d', -3)],默认是按照第一项排序的
        print sorted(items,key=lambda x:x[1]) # [('d', -3), ('a', 1), ('b', 2)],可以指定第二项排序
    
    

    方法二:

    
    '''
    根据字典中值的大小对字典中的项排序2-4imooc
    '''
    def sortedDictValues1():
       adict  = {'b':2,'a':1}
       items = adict.items()
       items.sort()
       return [value for key, value in items]
    
    # sortedDictValues1()
    
    def sortedDictValues2(adict):
       adict  = {'b':2,'a':1}
       keys = adict.keys()
       keys.sort()
       return [adict[key] for key in keys]
    
    def out1():
       dict1 = {'b':2,'a':1}
       print sortedDictValues1(dict1)   # [1, 2]
       print sorted(dict1.items(), key=lambda d: d[0])   #[('a', 1), ('b', 2)]
       print sorted(dict1.items(), key = itemgetter(0))  # [('a', 1), ('b', 2)]
    
    # out1()
    
    # 字典按顺序输出
    def dict_sorted3():
       dict1 = {'b':2,'a':1}
       keys = sorted(dict1.keys())
       dict2 = {}
       for i in keys:
           dict2.update({i:dict1[i]})
       print dict2
    

    相关文章

      网友评论

          本文标题:根据字典中值的大小对字典中的项排序

          本文链接:https://www.haomeiwen.com/subject/xspmlftx.html