Python Ranking Dictionary Return Rank

前端 未结 7 1364
我在风中等你
我在风中等你 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 06:44

    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
    

提交回复
热议问题