Backgroud:
Let's say I have a function (of course, in reality it would be a more complex function):
def f(x):
return str(x)
If I want to store values ββin order to avoid unnecessary recalculations, I can create dictas follows:
my_dict = {x: f(x) for x in range(5)}
But if I do not know in advance what value I can think of, for example 10, my_dict[10]obviously generates a KeyError.
One of the methods:
my_dict = {}
def get_value(x):
if x not in my_dict:
my_dict[x] = f(x)
return my_dict[x]
get_value(10)
Question:
It looks like defaultdict: is there a way to do an intuitive (but broken) job my_dict = defaultdict(f), i.e. When the key xdoes not exist, should it call f(x)instead f()to create a default value?