challenge ?

Raymond Hettinger python at rcn.com
Thu Mar 22 18:21:22 CET 2007


On Mar 22, 9:41 am, "alain" <alainpo... 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)

Try this:

>>> from operator import itemgetter
>>> my_dict = dict(a=10, b=5, c=8, d=12)
>>> for rank, (key, value) in enumerate(sorted(my_dict.items(), key=itemgetter(1))):
...	my_dict[key] = (value, rank)
>>> my_dict
{'a': (10, 2), 'c': (8, 1), 'b': (5, 0), 'd': (12, 3)}




More information about the Python-list mailing list