This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author steven.daprano
Recipients PartlyFluked, steven.daprano
Date 2020-12-23.11:51:42
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1608724302.38.0.797074521154.issue42723@roundup.psfhosted.org>
In-reply-to
Content
They don't do the same thing.

The dict comprehension requires a single key:value pair per loop. It accumulates values into a single dict. Try this:

    d = {}
    for key, value in items:
        print(id(d))
        d[key] = value

The ID doesn't change because it is the same dict each time.

Unpacking a dict doesn't produce a single key:value pair, except maybe by accident, so it is not usable in a dict comprehension.

Your second example doesn't modify a single dict, it **replaces** it with a new dict each time.

    d = {}
    for sub_dict in super_dict.values():
        print(id(d))
        d = { **d, **sub_dict }

The IDs will change through the loop as d gets replaced with a new dict each time. So this is not equivalent to a comprehension.

Also, the second would also be very inefficient. It unpacks the existing dict, then packs the values into a new dict, then unpacks it again, then repacks it into yet another dict, and so on.

Better:

    d = {}
    for sub_dict in super_dict.values():
        d.update(sub_dict)

But that's not equivalent to a dict comprehension either.
History
Date User Action Args
2020-12-23 11:51:42steven.dapranosetrecipients: + steven.daprano, PartlyFluked
2020-12-23 11:51:42steven.dapranosetmessageid: <1608724302.38.0.797074521154.issue42723@roundup.psfhosted.org>
2020-12-23 11:51:42steven.dapranolinkissue42723 messages
2020-12-23 11:51:42steven.dapranocreate