Python Ranking Dictionary Return Rank

前端 未结 7 1487
我在风中等你
我在风中等你 2021-02-10 06:40

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条回答
  •  萌比男神i
    2021-02-10 06:55

    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}
    

提交回复
热议问题