Sunil_Gupta
Sunil_Gupta

Reputation: 100

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 to Convert datalist into a dictionary assigning keys [868,869] and add values at index 2 and 3 of inner list having similar key value i.e 332.31,144.00 and 19.94, 8.64

 As Result would be : datadiict{868:['S00086', 640, 38.45], 869:['S00087', 476.31, 28.58]}

Please Suggest an effective solution , Thanks in Advance

Upvotes: 0

Views: 705

Answers (2)

Eugene Yarmash
Eugene Yarmash

Reputation: 149756

You could use itertools.groupby(), grouping on the 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 = {}

for k, group in groupby(sorted(datalist), key=lambda x: x[0]):
    for 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]}

Upvotes: 4

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The solution using itertools.groupby() and sum() functions:

import itertools
datalist = [[868, 'S00086', 640.80, 38.45], [869, 'S00087', 332.31, 19.94], [869, 'S00087', 144.00, 8.64]]

result = {}
# grouping inner lists by the 1st item value
for k,g in itertools.groupby(sorted(datalist), key=lambda x: x[0]):
    g = list(g)
    # summing up values for grouped items
    result[k] = g[0][1:] if len(g) == 1 else [g[0][1], sum(i[2] for i in g), sum(i[3] for i in g)]

print(result)

The output:

{868: ['S00086', 640.8, 38.45], 869: ['S00087', 476.31, 28.580000000000002]}

Upvotes: 1

Related Questions