在python中,结合3个dicts和按dict键之一进行排序的最有效方法是什么?

时间:2010-11-23 17:11:40

标签: python dictionary

示例:

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':'5678891234', 'name':'Alex Cheng'}
         ]

2 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:0)

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

这样 dicos 可能有任何长度