Python Ranking Dictionary Return Rank

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

    One way would be to examine the dictionary for the largest value, then remove it, while building a new dictionary:

    my_dict = x = {'a':10.1,'b':2,'c':5}
    i = 1
    new_dict ={}
    while len(my_dict) > 0:
        my_biggest_key = max(my_dict, key=my_dict.get)
        new_dict[my_biggest_key] = i
        my_dict.pop(my_biggest_key)
        i += 1
    print new_dict
    

提交回复
热议问题