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:
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.
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.('a', 0)
, so we want to only get the first element from that. key[0]
accomplishes that.value
.