天天看點

python對字典按key排序和按value排序。

  先上代碼:

>>> d = {:, :, :, :}
>>> d_k = sorted(d.items(), key=lambda x:x[]) # 按key排序,lambda x:x[0]表示取要排序的第一個元素排序
>>> d_k
[(, ), (, ), (, ), (, )]

>>> d_v = sorted(d.items(), key=lambda x:x[]) # 按value排序,lambda x:x[1]表示取第二個元素進行排序
>>> d_v
[(, ), (, ), (, ), (, )]
           

  看一下内置函數sorted詳解:

>>> help(sorted)
Help on built-in function sorted in module builtins:

sorted(iterable, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.

    A custom key function can be supplied to customize the sort order, and the
    reverse flag can be set to request the result in descending order.
           

  sorted一共有

iterable

,

key

,

reverse

這三個參數。其中iterable表示可以疊代的對象,例如可以是

dict.items()

dict.keys()

等,

key

是一個函數,用來選取參與比較的元素,

reverse

則是用來指定排序是倒序還是順序,預設是順序。