Python Ranking Dictionary Return Rank

前端 未结 7 901
臣服心动
臣服心动 2021-02-10 06:09

I have a python dictionary:

x = {\'a\':10.1,\'b\':2,\'c\':5}

How do I go about ranking and returning the rank value? Like getting back:

7条回答
  •  执笔经年
    2021-02-10 06:56

    You could do like this,

    >>> x = {'a':10.1,'b':2,'c':5}
    >>> m = {}
    >>> k = 0
    >>> for i in dict(sorted(x.items(), key=lambda k: k[1], reverse=True)):
            k += 1
            m[i] = k
    
    
    >>> m
    {'a': 1, 'c': 2, 'b': 3}
    

提交回复
热议问题