[Tutor] help with sorted()

Kent Johnson kent37 at tds.net
Sun Aug 17 22:50:26 CEST 2008

On 8/17/08, Rick Pasotto <rick at niof.net> wrote:
> I have a dictionary that looks like: d = {k:[v1,[v2,v3,v4]]}
> v1,v2,v3,v4 are integers.
> I want to print the dictionary sorted by v1, high to low.

Do you want just the keys, or the key/value pairs, or what?

> sorted(d,operator.itemgetter(0),reverse=True)
> gives me the keys in some order different than if I just looped through
> the dictionary and not in key order but also not in any order that I can
> see. It really appears random.

This will give you the keys in order by their first letter (assuming
the keys are strings).

> sorted(d) does give me a sorted list of keys.

Assuming you want the keys sorted by v1. You have to write a function
which, given a key, returns v1. That would be
def getv1(key):
  return d[key][0]

Then use this as the sort key:
sorted(d, key=getv1, reverse=True)


More information about the Tutor mailing list