views:

73

answers:

3

I have this:

dictionary = { (month, year) : [int, int, int] }

I'd like to get a list of tuples/lists with the ordered data(by month and year):

#example info
list = [(8,2010,2,5,3),(1,2011,6,7,8)...]

I've tried several times but I can't get to a solution.

Thanks for your help.

+5  A: 

Don't use as your identifier built-in names -- that's a horrible practice, without any advantages, and it will land you in some peculiar misbehavior eventually. So I'm calling the result thelist (an arbitrary, anodyne, just fine identifier), not list (shadowing a built-in).

import operator

thelist = sorted((my + tuple(v) for my, v in dictionary.iteritems()),
                 key = operator.itemgetter(1, 0))
Alex Martelli
+1 better than my answer :-)
Adam Bernier
thanks for your help Alex, I really appreciate it.I don't use the identifiers "dictionary" and "list" in my code, I used them for the example to be clear :). Looks like I failed.
mfalcon
@mfalcon, you're welcome! `dictionary` was and is just fine... it's `list` that, used as a user-chosen identifier, rings alarms bells for me (unfortunately, many built-in names, such as `set`, `file`, `tuple`, `sorted`, `type`, `super`, `unicode`, `property`, `range`, ..., **are** "attractive nuisances" in tempting the unwary to unsound shadowing, being also nice, common, attractive, descriptive English words -- so it's a frequent problem and anybody who often tries to help newbies grows very sensitive to it;-).
Alex Martelli
A: 

Something like this should get the job done:

>>> d = { (8, 2010) : [2,5,3], (1, 2011) : [6,7,8], (6, 2010) : [11,12,13] }
>>> sorted((i for i in d.iteritems()), key=lambda x: (x[0][1], x[0][0]))
[((6, 2010), [11, 12, 13]), ((8, 2010), [2, 5, 3]), ((1, 2011), [6, 7, 8])]

(Assuming the lambda should sort first by year, then month.)

See Alex Martelli's better answer for how to use itemgetter to solve this problem.

Adam Bernier
This gives a more deeply indented list than the OP was asking for, while my A gives him exactly the list of plain tuples he gives as an example (and as a bonus avoids any need for `lambda`;-).
Alex Martelli
@Alex: good point :-) I reference your answer in mine. Thanks, as always, for sharing your vast expertise.
Adam Bernier
@Adam, you're welcome!
Alex Martelli
A: 

This is a very concise way of doing what you ask.

l = [(m, y) + tuple(d[(y, m)]) for y, m in sorted(d)]
freegnu