How to automatically create a value from a non-existing key using a function

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?

+4
2

dict. __missing__ . , __missing__ . - .

from collections import UserDict
class MyDict(UserDict):
    def __missing__(self, key):
        self[key] = 2*key
        return self[key]

if __name__ == '__main__': # test
    a = MyDict((x, 2*x) for x in range(5))
    print(a)
    # {0: 0, 1: 2, 2: 4, 3: 6, 4: 8}
    a[5]
    # 10
    print(a)
    # {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5:10}

, UserDict , .

.

+2

defaultdict __missing__:

from collections import defaultdict
class betterdefault(defaultdict):
    def __missing__(self, key):
        return self.default_factory(key)

, throw KeyError, self.default_factory - None, - , . , , .

+3

Source: https://habr.com/ru/post/1680270/


All Articles