Python Forum

Full Version: Unpacking a dict with * or **
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I can unpack a dict with the ** operator. But something strange happens if I try to unpack it with *. This may be obvious given that the * operator unpacks a tuple or list. But watch this:

x = {'a': 7, 'b': 8}
print(*x)


That works and the output is "a b" but this does not:

z = *x
print(z)


So, in the first case when print is called it seems the def print(*args) has the effect of **x but how and why if the second example does not work? Why doesn't the code first execute *x and then pass the result to print()? If it could do that then why doesn't the second example work?
*x is not a valid Python expression, it cannot be evaluated. What would its value be? On the other hand func(*x) is a valid expression. There is no unary operator * or **.
*x unpacks x into two objects, 'a' and 'b'. This works fine when used in a function call. print(*x) becomes print('a', 'b'). This cannot work here:
z = *x
z can reference one object, but *x returns two. To get the two objects you need to use two variables and unpack like this:
y, z = x
Or you could unzip into a container like this:
z = (*x,)
print(z)
Output:
('a', 'b')
I'm sure there's a name for this, but I'm unsure what that name is, but you can use a * in the print() call, ahead of an iterative object. I use it for displaying the contents of a list object, for one. As an example: rather than print(lst) which displays the 'object', I'll sometimes use print(*lst) which displays the items.
(Nov-30-2023, 02:51 PM)Gribouillis Wrote: [ -> ]*x is not a valid Python expression, it cannot be evaluated. What would its value be? On the other hand func(*x) is a valid expression. There is no unary operator * or **.

Thank you. I originally thought it was a unary operator that would unpack x. But then that unary operator would be a function and functions return scalars or tuples, a pack not unpack of results. If not a unary operator than what? Your response made me think. It seems like * and ** are part of the language syntax and the language parser treats them like an operator in certain cases. Thank you.