Python 按照字典值对字典进行排序

  • 方法一:

    >>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}
    >>> sorted(xs.items(), key=lambda item: item[1])
    [('d', 1), ('c', 2), ('b', 3), ('a', 4)]
  • 方法二:

    >>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}
    >>> import operator
    >>> sorted(xs.items(), key=operator.itemgetter(1))
    [('d', 1), ('c', 2), ('b', 3), ('a', 4)]
本作品采用《CC 协议》,转载必须注明作者和本文链接
好好写代码,娶个宝宝回家。
Michael001
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!