collection中OrderedDict使用方法
阿新 • • 發佈:2018-12-17
本文介紹了OrderedDict的一個使用場景,根據元素型別分割一個OrderDict,分割後的型別為
{
key1:OrderedDict1,
key2:OrderedDict2
}
下面是程式碼:
from collections import OrderedDict class order(object): def __init__(self,id,symbol,price): self.id = id self.symbol=symbol self.price = price orderdict = OrderedDict() orderdict['110']=order('001','btc',100) orderdict['200']=order('002','usdt',200) orderdict['333']=order('003','btc',300) def separate(orderdict): sum = {} for key,order in orderdict.items(): if sum.get(order.symbol): sum[order.symbol][order.id] = order else: sum[order.symbol] = OrderedDict([(order.id,order)]) return sum if __name__ == '__main__': print(separate(orderdict))