Message383644
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. |
|
Date |
User |
Action |
Args |
2020-12-23 11:51:42 | steven.daprano | set | recipients:
+ steven.daprano, PartlyFluked |
2020-12-23 11:51:42 | steven.daprano | set | messageid: <1608724302.38.0.797074521154.issue42723@roundup.psfhosted.org> |
2020-12-23 11:51:42 | steven.daprano | link | issue42723 messages |
2020-12-23 11:51:42 | steven.daprano | create | |
|