Home > Back-end >  How to find previous element in ordered dict which has a looked up value
How to find previous element in ordered dict which has a looked up value

Time:04-09

I have an ordered dict with hours as keys, I want to find the last hour before the one given which has a given value as a value, if there is no such hour I want to return zero.

def get_previous_hour(od: OrderedDict, value: str, hour: int):
    pass

For instance for this input:

od=Ordereddict({1:"ala", 2:"a", 3:"a", 4: "dog",5:"a" })
hour=3
value="a"

it should return 2, beacuse it was the last time before 3 that "a" was a value.

For this input

od=Ordereddict({1:"ala", 2:"a", 3:"a", 4: "dog",5:"a" })
hour=5
value="a"

it should return 3. And for this input:

od=Ordereddict({1:"ala", 2:"a", 3:"a", 4: "dog",5:"a" })
hour=5
value="dog"

it should return 4. It is the first time I am using ordered dicts.

CodePudding user response:

Try:

hour = 5
value = "a"

prev_k = next(k for k, v in reversed(od.items()) if k < hour and v == value)
print(prev_k)

Prints:

3

CodePudding user response:

You can do this with a deque like this:

from collections import OrderedDict, deque

od = OrderedDict({1:"ala", 2:"a", 3:"a", 4: "dog",5:"a" })
dq = deque([None, None], maxlen=2)
hour = 3
value = 'a'
for k, v in od.items():
    if k > hour:
        break
    if v == value:
        dq.append(k)
print(dq[0] or dq[1])

Output:

2
  • Related