0

The following works fine:

from operator import itemgetter
d = { "a":(4,15), "c":(3,2), "b":(12,6) }
for k, v in sorted(d.items(), key=itemgetter(1)):
    print k, v

This returns:

c (3, 2)
a (4, 15)
b (12, 6)

But I would like to sort by second element of v: [15, 2, 6]

Get the impression for a dict this is not possible. True?

I looked around, but cannot seem to find... sorting by v means the order of items is important I see.

jpp
  • 134,728
  • 29
  • 196
  • 240
thebluephantom
  • 11,806
  • 6
  • 26
  • 54

1 Answers1

2

There is no native function composition in Python.

But the 3rd party toolz library does allow this:

from operator import itemgetter
from toolz import compose

d = { "a":(4,15), "c":(3,2), "b":(12,6) }

for k, v in sorted(d.items(), key=compose(itemgetter(1), itemgetter(1))):
    print(k, v)

Alaternatively, you can use an anonymous lambda function:

for k, v in sorted(d.items(), key=lambda x: x[1][1]):
    print(k, v)

Related: Nested lambda statements when sorting lists

jpp
  • 134,728
  • 29
  • 196
  • 240