I'm playing around with dict
comprehensions, and trying PEP572 (the :=
operator), in an example like this:
columns = {'idx', 'class_name'}
# populate them somehow
# ...
retval = {names[idx]:idx for idx in range(len(names)) if (names := list(columns))}
So basically, a dict
that contains the item in the set
and a value that iterates over it.
However, names
seems to be an UnboundLocalError
.
The below is what I'm trying to do, capture an alias of an outside variable of the scope of the comprehension:
names = list(columns)
retval = {names[idx]:idx for idx in range(len(names))}
Why is that an error?
Edit
Trying this within the captured columns
:
retval = {names[idx]:idx for idx in range(len(names:= list(columns)))}
produced a more meaningful IMHO error:
SyntaxError: assignment expression cannot be used in a comprehension iterable expression
So, as answered below, this isn't the way in which the walrus operator is meant to be used.