开发者

Sorted dict to list

开发者_如何学运维

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.


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))


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.


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜