[Python] defaultdict `.get` returns item and not none after calling after `[]` operator

Discussão em 'Python' iniciado por Stack, Janeiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    I ran this code:

    from collections import defaultdict
    my_dict = defaultdict(lambda: 6, a=7)
    print(repr(my_dict.get("a")))
    print(repr(my_dict.get("b")))
    print(repr(my_dict["b"]))
    print(repr(my_dict.get("b")))


    And the output was:

    7
    None
    6
    6


    Ran it on: 3.13.1 (tags/v3.13.1:0671451, Dec 3 2024, 19:06:28) [MSC v.1942 64 bit (AMD64)].

    As you can see, when I called my_dict.get("b") before calling my_dict["b"], it returned None. But after I called my_dict.get("b"), it returned None.

    According to the docs, it should return the default computed by the factory only at the my_dict["b"] call (__getitem__() method), so why at the second call of: my_dict.get("b"), it returned the computed value? Is it an expected value, or a bug?

    Continue reading...

Compartilhe esta Página