Python Ranking Dictionary Return Rank

前端 未结 7 1361
我在风中等你
我在风中等你 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:01

    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
    

提交回复
热议问题