Steven D'Aprano <[email protected]> added the comment:
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.
----------
nosy: +steven.daprano
resolution: -> not a bug
stage: -> resolved
status: open -> closed
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue42723>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com