A question was asked here on SO, a few minutes ago, on sorting dictionary keys based on their values.
I just read about the operator.itemgetter
method of sorting a few days back and decided to try that, but it doesn't seem to be working.
Not that I have any problems with the answers presented to the questions, I just wanted to try this with operator.itemgetter
.
So the dict was:
>>> mydict = { 'a1': ['g',6],
'a2': ['e',2],
'a3': ['h',3],
'a4': ['s',2],
'a5': ['j',9],
'a6': ['y',7] }
I tried this:
>>> l = sorted(mydict.itervalues(), key=operator.itemgetter(1))
>>> l
[['e', 2], ['s', 2], ['h', 3], ['g', 6], ['y', 7], ['j', 9]]
And this works as I want it to. However, since I don't have the complete dictionary (mydict.itervalues()
), I tried this:
>>> complete = sorted(mydict.iteritems(), key=operator.itemgetter(2))
This doesn't work (as I expected it to).
So how do I sort the dict using operator.itemgetter
and call itemgetter
on the nested key - value pair.