Python Ranking Dictionary Return Rank

前端 未结 7 914
臣服心动
臣服心动 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:51

    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)])
    

提交回复
热议问题