Reputation: 77
I've been playing around with dictionary comprehension, and just as I thought I got the hang of it, I received the error: SyntaxError: dict unpacking cannot be used in dict comprehension
This is the example that I tried:
a = {'a': 1, 'b': 2}
b = {'b': 3, 'c': 4}
{**a, **b} # {'a': 1, 'b': 3, 'c': 4}
{ **c for c in [a, b] } # SyntaxError: dict unpacking cannot be used in dict comprehension
I have seen similar posts which provide work around to this particular issue (mainly Dict merge in a dict comprehension), but I have never seen an explanation as to why it happens.
I found this issue40715, but I couldn't find an answer there either.
If anyone can shed some light on the subject, or redirect me to an article or whatnot I'd be grateful.
Upvotes: 6
Views: 933
Reputation: 2074
Stumbled recently into this. I think the main problem is that **c
is a pointer to what is stored in the iterator, which is going to change the moment you iterate, so eventually reassigning the pointer to something else would have the effect to loose the previous reference. To merge different objects together, you need to have the pointers to actually references those objects already.
Upvotes: 1