Python Ranking Dictionary Return Rank

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

    First sort by value in the dict, then assign ranks. Make sure you sort reversed, and then recreate the dict with the ranks.

    from the previous answer :

    import operator
    x={'a':10.1,'b':2,'c':5}
    sorted_x = sorted(x.items(), key=operator.itemgetter(1), reversed=True)
    out_dict = {}
    for idx, (key, _) in enumerate(sorted_x):
        out_dict[key] = idx + 1
    print out_dict
    

提交回复
热议问题