[Python] python defaultdict, get(..) vs. ["..."] [duplicate]

Discussão em 'Python' iniciado por Stack, Junho 4, 2025.

  1. Stack

    Stack Membro Participativo

    Is somebody able to explain this strange python behavior?

    >>> from collections import defaultdict

    >>> d = defaultdict(lambda: "foo")
    >>> d
    >>> defaultdict(<function <lambda> at 0x732ae877a480>, {})
    >>> d["x"]
    >>> 'foo'
    >>> d
    >>> defaultdict(<function <lambda> at 0x732ae877a480>, {'x': 'foo'})


    I interpret d[x] as a read access. However, the value of x gets stored in the dict, which is indeed a write access.
    Is this some caching mechanism for long evaluating lambdas?

    Now, when I use .get(...) instead of indexing, behaviour is different:

    >>> d.get("y")
    >>> <None>
    >>> d
    >>> defaultdict(<function <lambda> at 0x732ae877a480>, {'x': 'foo'})


    This time y is not stored in the dict and the returned value is None instead of foo.
    This is even more confusing as the value returned by d.get("y") or d["y"] is dependent on the order of the invocation of both.

    Continue reading...

Compartilhe esta Página