Do you know you can use ** (double asterisk) syntax to unpack dictionary?
what do I really mean by unpacking a dictionary? Let’s look at some examples and understand.
In this example, we have a dictionary named response. In the format function, we have used ** syntax before the response, which allows us to use keys in the dictionary as variables.
Similarly, let’s say we want to pass some arguments to the function (it could be positional or keyword args), we don’t have access values separately by keys, we can use ** before dictionary, and it will “spread” / ”separate” / ”unpack” key values in a dict and pass it to the function.
In the case of keyword argument, make sure argument names are the same as keys in dict object.
One more example is where we are unpacking two dictionaries inside a new dictionary, this operation merges our dictionary into a single dictionary.
In short, Unpacking is an operation that assigns elements in a list or dictionary to multiple variables. In the case of a dictionary, a variable name is the same as the key.
In the case of List/Tuple, we use * (single asterisk), and values are assigned as per the position of variables. It is really helpful when we are using positional arguments in a function.
I hope you have understood this concept. * is really useful syntax. We can use it in so many ways, Let’s talk about it in detail some other time.
Meanwhile, Follow me on Twitter for more useful tips and information on Python syntax & functionalities. Do reply with any questions/suggestions
Thanks for reading!