天天看点

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

则是用来指定排序是倒序还是顺序,默认是顺序。