Home > Blockchain >  find keys in dictionary of lists where a given value is less than or equal to the values in the dict
find keys in dictionary of lists where a given value is less than or equal to the values in the dict

Time:05-06

I have a dictionary of events and their timestamps stored in list of values. I want to return the key/keys (event) where a given timestamp is less or equal to a timestamps in the dictionary:

for e.g

{"foo" : [12:00:00, 12:00:01, 12:00:03, 12:00:04], 
 "bar" : [12:00:05, 12:00:08], 
 "baz" : [12:00:12, 12:00:20]}

I have a timestamp: 12:00:05. I want to be able to return all the keys (events) that happened on or before this timestamp from my dictionary.

currently, I used a brute force solution where I was comparing my timestamp with each value in the list of values and appending the keys in an output.I am sure there is an optimized solution for this problem.

My solution:

def fetch_event(logger_dict, ts):
   output = []
   for k, v in logger_dict.items():
     for i in v:
        if ts<=i: 
          output.append(i)
   return output

I would love to learn how this could be done in a more efficient way.

CodePudding user response:

I'd suggest not storing these events in a dictionary keyed by event name if you want to be able to look them up by time.

To convert your dictionary into a list of tuples sorted by time you could do:

>>> logger_list = sorted((t, e) for e, v in logger_dict.items() for t in v)

Then to efficiently get all elements before a given time you could use bisect:

>>> import bisect
>>> logger_list[:bisect.bisect(logger_list, ("12:00:05",))   1]
[('12:00:00', 'foo'), ('12:00:01', 'foo'), ('12:00:03', 'foo'), ('12:00:04', 'foo'), ('12:00:05', 'bar')]

CodePudding user response:

This can be done simply and work for timestamps as well.

specified_value = "12:00:05"
d =  {"foo" : ["12:00:00", "12:00:01", "12:00:03", "12:00:04"], "bar" : ["12:00:05", "12:00:08"], "baz" : ["12:00:12", "12:00:20"]}
[key for key in d if min(d[key]) <= specified_value]

If values are already sorted then

[key for key in d if d[key][0] <= specified_value]
  • Related