I'm working with Python 3.11. I have a dictionary whose keys are datetime objects and whose values are strings.
dates = {datetime.datetime(2022, 1, 1): "a",
datetime.datetime(2022, 5, 4): "b",
datetime.datetime(2022, 9, 25): "c",
datetime.datetime(2023, 5, 17): "d",
datetime.datetime(2023, 12, 15): "e",
datetime.datetime(2024, 3, 17): "f",
datetime.datetime(2024, 4, 3): "g"}
I would like to know if there is a way to remove all the elements that have already passed (other than iterating through all the elements). For example in this case datetime.datetime.now() = datetime.datetime(2024, 2, 9) so the result dictionary will be:
dates = {datetime.datetime(2024, 3, 17): "f",
datetime.datetime(2024, 4, 3): "g"}
This code works in case the dictionary is ordered by date (which may not be the case):
new_dates = {}
now = datetime.datetime.now()
for k, v in reversed(dates.items()):
if k < now:
break
new_dates[k] = v
But I would like to know if there is any other way without a loop or thay might work in a disorderly dictionary.
You could form a new Dictionary using a comprehension; order does not matter:
dates2 = {k:v for k, v in dates.items() if k > now}
which gives
{datetime.datetime(2024, 3, 17, 0, 0): 'f', datetime.datetime(2024, 4, 3, 0, 0): 'g'}
You want to use SortedDict in the sortedcontainers package. It behaves just like a dictionary, but has additional methods.
You will have to install it via pip.
# Binary search to find the index of the first element larger than now
index = dates.bisect_right(now)
# Delete everything now or below
del dates.keys()[:index]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With