![](/img/trans.png)
[英]What is the most efficient way to sum a dict with multiple keys by one key?
[英]In python, what's the most efficient way to combine 3 dicts and to sort by one of the dict's keys?
例:
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'}
]
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')
因此, dicos可能有任何长度
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.