Python Ranking Dictionary Return Rank

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

    Pretty simple sort-of simple but kind of complex one-liner.

    {key[0]:1 + value for value, key in enumerate(
                           sorted(d.iteritems(),
                                  key=lambda x: x[1],
                                  reverse=True))}
    

    Let me walk you through it.

    • We use enumerate to give us a natural ordering of elements, which is zero-based. Simply using enumerate(d.iteritems()) will generate a list of tuples that contain an integer, then the tuple which contains a key:value pair from the original dictionary.
    • We sort the list so that it appears in order from highest to lowest.
    • We want to treat the value as the enumerated value (that is, we want 0 to be a value for 'a' if there's only one occurrence (and I'll get to normalizing that in a bit), and so forth), and we want the key to be the actual key from the dictionary. So here, we swap the order in which we're binding the two values.
    • When it comes time to extract the actual key, it's still in tuple form - it appears as ('a', 0), so we want to only get the first element from that. key[0] accomplishes that.
    • When we want to get the actual value, we normalize the ranking of it so that it's 1-based instead of zero-based, so we add 1 to value.

提交回复
热议问题