challenge ?
Frank Benkstein
frank-python at benkstein.net
Thu Mar 22 13:11:46 EDT 2007
Hi,
On 22 Mar 2007 09:41:43 -0700
"alain" <alainpoint at yahoo.fr> wrote:
> I have a problem I wonder if it has been solved before.
> I have a dictionnary and I want the values in the dictionnary to be
> annotated with the rank that would be obtained by sorting the values
>
> def annotate_with_rank(my_dict):
> ....
> return my_annotated_dict
>
> In other words, any value a_value would become a 2-tuple
> (a_value,rank_of_a_value)
>
> I seek an elegant solution.
In your specification of the problem it is unclear what should be done
with duplicate values. My solution assigns every value a different
rank (starting from 0) such that the highest rank is len(my_dict) - 1.
def annotate_with_rank(my_dict):
items = my_dict.items()
items.sort(key = lambda (k, v): v)
return dict((k, (i, v)) for i, (k, v) in enumerate(items))
Best regards,
Frank Benkstein.
--
GPG (Mail): 7093 7A43 CC40 463A 5564 599B 88F6 D625 BE63 866F
GPG (XMPP): 2243 DBBA F234 7C5A 6D71 3983 9F28 4D03 7110 6D51
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20070322/12f75751/attachment.sig>
More information about the Python-list
mailing list