i tried to unpack dictionary keys to a variable with asterisk,but it raise error. but if i put a comma after a variable, it will works well! why this happen?
test_2 = {'x': 20,
'y': 60,
'z': 100
}
*d = test_2
print(d)
>>>SyntaxError: starred assignment target must be in a list or tuple
this one will works well:
*d, = test_2
print(d) #['x', 'y', 'z']
CodePudding user response:
It does not work because that is how the syntax was designed. If you read the error, the assignment has to be into a list or tuple.
You assigned into a variable.
test = {'a':1, 'b':2, 'c':3, 'd':4}
z, *y, x = test
y will take on the value of everything that is not the first and last items.
There are other ways of unpacking dictionary keys, python has many methods of doing this.
https://medium.com/swlh/how-to-pack-and-unpack-data-in-python-tuples-and-dictionaries-55d218c65674 this has a pretty good coverage of what you can do.
CodePudding user response:
The regular case is to unpack into a list* of variables:
a, b, c = some_iterable
* a tuple of variables to be pedantic
The "special case" is to unpack into a list where there are fewer variables than items to unpack, and one variable in the list takes all remaining items:
a, b, *c = some_very_long_iterable
This assigns the first and second item to a
and b
respectively, and all the rest to c
as a list.
Given this, what does *d = test_2
do…? It puts everything in test_2
into d
. Which is the same that d = test_2
would do. So the syntax *d = ...
has no specific useful meaning, and is hence a syntax error.
You may debate whether it should work or not, but the definition of an unpacking assignment is that the left-hand side needs to be a list of variables, one of which may have an asterisk. *d
isn't a list of variables. *d,
is. The comma makes the tuple.
CodePudding user response:
Instead of dictionary let's assume a list for simplicity:
test_2 = ['a', 'b', 'c']
*d = test_2
print(d)
Suppose the *d = test_2
works, then what would be the d
? It's going to be : ['x', 'y', 'z']
. Isn't it exactly same as d = test_2
?
I guess they didn't allow this syntax because it's pointless to have single starred assignment in the left hand side. That's why you get SyntaxError: starred assignment target must be in a list or tuple
.
When you put a comma after the *d
, you create a "tuple" which is a reasonable case to have "starred assignment" (usual unpacking with/without other symbols inside it like a, b, *rest = ...
).
*d, = test_2 # works
(*d,) = test_2 # works
[*d] = test_2 # works
*d = test_2 # doesn't work