Popping key causes dict derived from object to revert to object

Grant Edwards grant.b.edwards at gmail.com
Fri Mar 22 12:01:15 EDT 2024


On 2024-03-22, Loris Bennett via Python-list <python-list at python.org> wrote:

> Yes, I was mistakenly thinking that the popping the element would
> leave me with the dict minus the popped key-value pair.

It does.

> Seem like there is no such function.

Yes, there is. You can do that with either pop or del:

    >>> d = {'a':1, 'b':2, 'c':3}
    >>> d
    {'a': 1, 'b': 2, 'c': 3}
    >>> d.pop('b')
    2
    >>> d
    {'a': 1, 'c': 3}


    >>> d = {'a':1, 'b':2, 'c':3}
    >>> del d['b']
    >>> d
    {'a': 1, 'c': 3}

In both cases, you're left with the dict minus the key/value pair.

In the first case, the deleted value printed by the REPL because it
was returned by the expression "d.pop('b')" (a method call).

In the second case is no value shown by the REPL because "del d['b']"
is a statement not an expression.






More information about the Python-list mailing list