Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a dictionary of tuples in Python

I know there's tonnes of questions on python sorting lists/dictionaries already, but I can't seem to find one which helps in my case, and i'm looking for the most efficient solution as I'm going to be sorting a rather large dataset.

My data basically looks like this at the moment:

a = {'a': (1, 2, 3), 'b': (3, 2, 1)}

I'm basically creating a word list in which I store each word along with some stats about it (n, Sigma(x), Sigma(x^2) )

I want to sort it based on a particular stat. So far I've been trying something along the lines of:

b = a.items()
b.sort(key = itemgetter(1), reverse=True)

I'm not sure how to control which index it is sorted based on when its effectively a list of tuples of tuples? I guess I effectively need to nest two itemgetter operations but not really sure how to do this.

If there's a better data structure I should be using instead please let me know. Should I perhaps create a small class/struct and then use a lambda function to access a member of the class?

Many Thanks

like image 702
Dave White Avatar asked Sep 08 '11 14:09

Dave White


1 Answers

Something like this?

>>> a = {'a': (1, 2, 3), 'b': (3, 2, 1)}
>>> b = a.items()
>>> b
[('a', (1, 2, 3)), ('b', (3, 2, 1))]
>>> b.sort(key=lambda x:x[1][2])  # sorting by the third item in the tuple
>>> b
[('b', (3, 2, 1)), ('a', (1, 2, 3))]
like image 128
Tim Pietzcker Avatar answered Sep 28 '22 23:09

Tim Pietzcker