Requirement
I would like to define a defaultdict
that returns the value of the largest key, if the key that I am providing is not in the dictionary. Basically I am looking for a way to store config information with the twist, that values default to their last defined values.
Solution so far
My implementation is as follows:
from collections import defaultdict
d = defaultdict(lambda: d[max(d.keys())])
d.update({2010: 10, 2011: 20, 2013: 30 })
for year in [2010, 2011, 2013, 2014]:
print(f"{year}: {d[year]}")
which correctly produces:
2010: 10
2011: 20
2013: 30
2014: 30
(a more elaborate version could also return values for keys smaller than the smallest).
Question
Is there a more elegant way to define the lambda function without the requirement that you know the dictionary's name?