So, i want to sum multiple values of a list of dictionaries, this is what i made so far, it works but obviusly there is a lot of problems and inefficiency
# plate: license plate of the vehicule
# distance: the distance traveled by the vehicule in KM
# time: the time the vehicule travels in minutes
from collections import defaultdict
vehicles = [
{"plate":"ABC123", "distance":80.3, "time":180},
{"plate":"ABC123", "distance":80.3, "time":180},
{"plate":"XYZ246", "distance":40.0, "time":30},
{"plate":"XYZ246", "distance":60.7, "time":100},
{"plate":"ABC123", "distance":70.2, "time":200},
{"plate":"MNL357", "distance":40.3, "time":70}
]
returnList = []
dst, time = defaultdict(int), defaultdict(int)
for v in vehicles:
dst[v["plate"]] = v["distance"]
time[v["plate"]] = v["time"]
dst = dict(dst)
time = dict(time)
for i in dst:
returnList.append({"plate":i,"distance":dst[i], "time":time[i]})
print(returnList)
In this case, i want to sum the distance and time of a license plate, its result is
[
{'plate': 'ABC123', 'distance': 230.8, 'time': 560},
{'plate': 'XYZ246', 'distance': 100.7, 'time': 130},
{'plate': 'MNL357', 'distance': 40.3, 'time': 70}
]
Thanks!
CodePudding user response:
You could do this:
In [6]: from collections import defaultdict
...: vehicles = [
...: {"plate":"ABC123", "distance":80.3, "time":180},
...: {"plate":"ABC123", "distance":80.3, "time":180},
...: {"plate":"XYZ246", "distance":40.0, "time":30},
...: {"plate":"XYZ246", "distance":60.7, "time":100},
...: {"plate":"ABC123", "distance":70.2, "time":200},
...: {"plate":"MNL357", "distance":40.3, "time":70}
...: ]
In [7]: import itertools as it
In [8]: keyfunc = lambda x: x['plate']
In [9]: vehicle_groups = it.groupby(sorted(vehicles, key=keyfunc), keyfunc)
In [10]: [{'plate':p, 'distance':sum(x['distance'] for x in g), 'time':sum(y['ti
...: me'] for y in g)} for p, g in vehicle_groups]
Out[10]:
[{'plate': 'ABC123', 'distance': 230.8, 'time': 0},
{'plate': 'MNL357', 'distance': 40.3, 'time': 0},
{'plate': 'XYZ246', 'distance': 100.7, 'time': 0}]
CodePudding user response:
Could you expand on what result you're trying to get? Bit unclear.