Python 3 sort a dict by its values

后端 未结 6 1319
伪装坚强ぢ
伪装坚强ぢ 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:18

    itemgetter (see other answers) is (as I know) more efficient for large dictionaries but for the common case, I believe that d.get wins. And it does not require an extra import.

    >>> d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
    >>> for k in sorted(d, key=d.get, reverse=True):
    ...     k, d[k]
    ...
    ('bb', 4)
    ('aa', 3)
    ('cc', 2)
    ('dd', 1)
    

    Note that alternatively you can set d.__getitem__ as key function which may provide a small performance boost over d.get.

提交回复
热议问题