开发者

In python, what's the most efficient way to combine 3 dicts and to sort by one of the dict's keys?

Example:

list1 = {'52': {'timestamp':'1234567890', 'name':'Jason Bourne'},
         '42': {'timestamp':'2345678891', 'name':'Sarah Parker'}
         }

list2 = {'61': {'timestamp':'3456789012', 'name':'Mike Williams'},
         '12': {'timestamp':'4567889123', 'name':'Robert Tissone'}
         }

list3 = {'56': {'timestamp':'4567890123', 'name':'Peter Blake'},
         '71': {'timestamp':'5678891234', 'name':'Alex Cheng'}
         }

//Best way to combine list1, list2, and list3 and sort by timestamp

result = [ {'timestamp':'1234567890', 'name':'Jason Bourne'},
           {'timestamp':'2345678891', 'name':'Sarah Parker'},
           {'timestamp':'3456789012', 'name':'Mike Williams'},
           {'timestamp':'4567889123', 'name':'Robert Tissone'},
           {'timestamp':'4567890123', 'name':'Peter Blake'},
           {'timestamp':开发者_如何学C'5678891234', 'name':'Alex Cheng'}
         ]


sorted(itertools.chain(list1.itervalues(), list2.itervalues(),
    list3.itervalues()), key=operator.itemgetter('timestamp'))


from itertools import chain
from operator import itemgetter

def sortedchain(dicos, key):
    return sorted(chain(v for d in dicos for v in d.values()), key=itemgetter(key))

dicos=[list1, list2, list3]
sortedvalues = sortedchain(dicos, 'timestamp')  

So that dicos may have any lenght

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜