Python Forum
Unpacking a dict with * or ** - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Unpacking a dict with * or ** (/thread-41225.html)



Unpacking a dict with * or ** - msrk - Nov-30-2023

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?


RE: Unpacking a dict with * or ** - Gribouillis - Nov-30-2023

*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 **.


RE: Unpacking a dict with * or ** - deanhystad - Nov-30-2023

*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')



RE: Unpacking a dict with * or ** - rob101 - Nov-30-2023

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.


RE: Unpacking a dict with * or ** - msrk - Dec-02-2023

(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.