Convert python list into dictionary and adding values having same keys -


datalist = [[868, 's00086', 640.80, 38.45], [869, 's00087', 332.31, 19.94], [869, 's00087', 144.00, 8.64],] 

how convert datalist dictionary assigning keys [868,869] , add values @ index 2 , 3 of inner list having similar key value i.e 332.31,144.00 , 19.94, 8.64

 result : datadiict{868:['s00086', 640, 38.45], 869:['s00087', 476.31, 28.58]} 

please suggest effective solution , in advance

you use itertools.groupby(), grouping on first item of each sublist:

from itertools import groupby  datalist = [[868, 's00086', 640.80, 38.45], [869, 's00087', 332.31, 19.94], [869, 's00087', 144.00, 8.64],] datadict = {}  k, group in groupby(sorted(datalist), key=lambda x: x[0]):     v in group:         if k not in datadict:             datadict[k] = v[1:]         else:             datadict[k][1] += v[2]             datadict[k][2] += v[3] print(datadict)  # {868: ['s00086', 640.8, 38.45], 869: ['s00087', 476.31, 28.580000000000002]} 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -