challenge ?

Frank Benkstein frank-python at benkstein.net
Thu Mar 22 13:25:11 EDT 2007


Hi, again,

On Thu, 22 Mar 2007 18:11:46 +0100
Frank Benkstein <frank-python at benkstein.net> wrote:

> 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.

The two other possibilities were to still make len(my_dict) ranks but
assign equal values an equal rank. That would mean that some ranks are
untaken. Or, lastly, to make only as much ranks as there are unique
values.
 
> 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))

def annotate_with_rank_2(my_dict):
    values = my_dict.values()
    values.sort()
    return dict((k, (values.index(v), v)) for k, v in my_dict.iteritems())

def annotate_with_rank_3(my_dict):
    values = list(set(my_dict.itervalues()))
    values.sort()
    return dict((k, (values.index(v), v)) for k, v in my_dict.iteritems())

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/b0e28161/attachment.sig>


More information about the Python-list mailing list