If your dicts are in sorted order based on the 'remote'
key , you can group them by the 'remote'
key and get the last entry which will be the latest timestamp.
l = [{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3}]
from itertools import groupby
from operator import itemgetter
l[:] = (list(v)[-1] for _, v in groupby(l,key=(itemgetter("remote"))))
print(l)
[{'timestamp': 1, 'remote': '1', 'quantity': 1.0},
{'timestamp': 3, 'remote': '2', 'quantity': 1.0}]
l[:]
changes the original list, (list(v)[-1] for k,v in groupby(l,key=(itemgetter("remote"))))
is a generator expression which means we don't need to store all the content in memory at once which if memory is also an issue will help.
This will also work for unsorted data once the dupes are always together and the latest dupe comes last:
l = [{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '4', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3}]
l[:] = (list(v)[-1] for k,v in groupby(l, key=(itemgetter("remote"))))
print(l)
[{'timestamp': 1, 'remote': '1', 'quantity': 1.0}, {'timestamp': 1, 'remote': '4', 'quantity': 1.0}, {'timestamp': 3, 'remote': '2', 'quantity': 1.0}]
Or if the dupes are not sorted get the max based on timestamp:
l = [{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '4', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2}]
l[:] = (max(v,key=itemgetter("timestamp")) for _, v in groupby(l, key=(itemgetter("remote")))
[{'timestamp': 1, 'remote': '1', 'quantity': 1.0}, {'timestamp': 1, 'remote': '4', 'quantity': 1.0}, {'timestamp': 3, 'remote': '2', 'quantity': 1.0}]
If you were going to sort you should do an inplace reverse sort by the remote key, them call next on the grouping v
to get the latest:
l = [{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '4', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2}]
l.sort(key=itemgetter("remote"),reverse=True)
l[:] = (next(v) for _, v in groupby(l, key=(itemgetter("remote"))))
print(l)
Sorting will change the order of the dicts though so that may not be suitable for your problem, if your dicts
are in order like your input then you don't need to worry about sorting anyway.