0

I have a Python app that gets speed data changes from devices for one day and graphs them using matplotlib. I currently store that data in dictionary like this:

port_1_info = {datetime.datetime(2022, 12, 4, 4, 27, 24): 158,
               datetime.datetime(2022, 12, 4, 4, 27, 25): 44,
               datetime.datetime(2022, 12, 4, 4, 27, 32): 90,
               datetime.datetime(2022, 12, 4, 4, 27, 37): 158, 
               datetime.datetime(2022, 12, 4, 4, 27, 41): 181, ...}

port_2_info = { ... } # same format different times

I have two sets of data in this format: one for port 1 and the other for port 2. I would like to combine them into one set of data that is the sum of speeds throughout the day. One issue is that the time intervals are different, because the speed changes happen randomly.

How would I go about merging them? I have already sorted each dictionary but am struggling to find a way to sum them properly.

I tried using a third dictionary and input all data into it but can't find an algorithm that will make it work properly

Stef
  • 13,242
  • 2
  • 17
  • 28
Marsel
  • 9
  • 1
  • Here's a very simplistic approach: Initialize `t` to midnight December 4th, then count forward 1 second each time through the loop, and yield a (t, speed1, speed2) tuple. It is verbose, but it should unblock you. (Clearly there are ways to improve upon this, such as merge sort of both sets of timestamps.) – J_H Mar 07 '23 at 00:31
  • This is somewhat similar to [Minimum number of platforms required for a railway station?](https://stackoverflow.com/questions/62694219/minimum-number-of-platforms-required-for-a-railway-station/62697797#62697797) – Stef Mar 07 '23 at 11:24
  • *"One issue is that the time intervals are different, because the speed changes happen randomly."* I don't see time intervals in your data, only simple times. The whole problem is a bit unclear to me, could you clarify? For instance, if you just merged the two lists and sorted the merge list, would that solve your problem? If not, why not? – Stef Mar 07 '23 at 11:26
  • Note that I said "lists" and not "dict" because if you merge two dicts and one key is in both dicts, then one of the values will be erased. For instance `{1: 10, 2: 20} | {2: 30}` will simplify to `{1: 10, 2: 30}`, and the `2: 20` is lost. But if you merge them as lists then no value is lost: `sorted(chain({1: 10, 2: 20}.items(), {2: 30}.items()))` simplifies to `[(1, 10), (2, 20), (2, 30)]` (with `chain` from `itertools`, not really needed but convenient) – Stef Mar 07 '23 at 11:35
  • As for summing once they're merged, just do `result = {}; total = 0; for time, increment in sorted_list: total += increment; result[time] = total` – Stef Mar 07 '23 at 11:40

0 Answers0