wormwood_3 wrote:
>>> You can use d.__getitem__ as the key function for a sort of the keys. 
>>> __getitem__() is the special method that is called for indexing a 
>>> dictionary (or a list).
> 
> Just curious: Is there a reason to use __getitem__() over itemgetter
> (used in the example in my reply)?

The results are different. My code gives a list of keys, sorted by 
value, which was how I interpreted the request. Your code gives a list 
of key, value pairs, sorted by value.

It's easy enough to change your list to just keys with a list 
comprehension. Then you are essentially doing a sort using 
decorate-sort-undecorate (except the decorate step builds the tuples in 
the wrong order). You could think of the sort using key=d.__getitem__ as 
the modern equivalent of your DSU sort.

OTOH if the OP really *wants* a sorted list of key, value pairs, your 
version is fine.

>>> In [24]: d = {'a':21.3, 'b':32.8, 'c': 12.92}
>>> In [26]: sorted(d.keys(), key=d.__getitem__, reverse=True)
> 
> I think Shawn would want to leave off "reverse=True". The default is
> least to greatest, which is what he wanted, I think.

Possibly. He did say "least to greatest" but his example output is 
greatest to least.

Kent
_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to