Python Ranking Dictionary Return Rank

前端 未结 7 1366
我在风中等你
我在风中等你 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条回答
  •  迷失自我
    2021-02-10 07:00

    In [23]: from collections import OrderedDict
    
    In [24]: mydict=dict([(j,i) for i, j in enumerate(x.keys(),1)])
    
    In [28]: sorted_dict = sorted(mydict.items(), key=itemgetter(1))
    
    In [29]: sorted_dict
    Out[29]: [('a', 1), ('c', 2), ('b', 3)]
    In [35]: OrderedDict(sorted_dict)
    Out[35]: OrderedDict([('a', 1), ('c', 2), ('b', 3)])
    

提交回复
热议问题