Python 2.5 dictionary 2 key sort

后端 未结 6 1753
灰色年华
灰色年华 2021-01-01 19:47

I have a dictionary of 200,000 items (the keys are strings and the values are integers).

What is the best/most pythonic way to print the items sorted by descending v

6条回答
  •  温柔的废话
    2021-01-01 20:21

    >>> keys = sorted(a, key=lambda k: (-a[k], k))
    

    or

    >>> keys = sorted(a)
    >>> keys.sort(key=a.get, reverse=True)
    

    then

    print [(key, a[key]) for key in keys]
    [('keyB', 2), ('keyA', 1), ('keyC', 1)]
    

提交回复
热议问题