简体   繁体   中英

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.

这是一种非常简洁的方式来做你所要求的。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM