Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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':'5678891234', 'name':'Alex Cheng'}
         ]
like image 901
ensnare Avatar asked Dec 02 '25 20:12

ensnare


1 Answers

sorted(itertools.chain(list1.itervalues(), list2.itervalues(),
    list3.itervalues()), key=operator.itemgetter('timestamp'))
like image 196
Ignacio Vazquez-Abrams Avatar answered Dec 04 '25 11:12

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!