Python 3 sort a dict by its values

后端 未结 6 1318
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 14:20

The only methods I found work for python2 or return only list of tuples.

Is it possible to sort dictionary, e.g. {\"aa\": 3, \"bb\": 4, \"cc\": 2, \"dd\": 1}

6条回答
  •  难免孤独
    2020-12-07 15:17

    To sort dictionary, we could make use of operator module. Here is the operator module documentation.

    import operator                             #Importing operator module
    dc =  {"aa": 3, "bb": 4, "cc": 2, "dd": 1}  #Dictionary to be sorted
    
    dc_sort = sorted(dc.items(),key = operator.itemgetter(1),reverse = True)
    print dc_sort
    

    Output sequence will be a sorted list :

    [('bb', 4), ('aa', 3), ('cc', 2), ('dd', 1)]
    

    If we want to sort with respect to keys, we can make use of

    dc_sort = sorted(dc.items(),key = operator.itemgetter(0),reverse = True)
    

    Output sequence will be :

    [('dd', 1), ('cc', 2), ('bb', 4), ('aa', 3)]
    

提交回复
热议问题