Python 3 sort a dict by its values

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

    You can sort by values in reverse order (largest to smallest) using a dictionary comprehension:

    {k: d[k] for k in sorted(d, key=d.get, reverse=True)}
    # {'b': 4, 'a': 3, 'c': 2, 'd': 1}
    

    If you want to sort by values in ascending order (smallest to largest)

    {k: d[k] for k in sorted(d, key=d.get)}
    # {'d': 1, 'c': 2, 'a': 3, 'b': 4}
    

    If you want to sort by the keys in ascending order

    {k: d[k] for k in sorted(d)}
    # {'a': 3, 'b': 4, 'c': 2, 'd': 1}
    

    This works on CPython 3.6+ and any implementation of Python 3.7+ because dictionaries keep insertion order.

提交回复
热议问题