What is double star ** for ?
Double star in python syntax is most used for pack
or unpack
a dictionary.
In function call
It is used to unpack the dictionaries
and pass items in the dictionary as keyword arguments to the function.
def function(a, b):
return a + b
params = {'a': 1, 'b': 2}
print(function(**params)) # prints: 3
In function argument
It is used to allow the function to accept an arbitrary number of keyword arguments. These arguments are stored in a dictionary. Here's an example:
def function(**kwargs):
for key, value in kwargs.items():
print(f'{key}:{value}')
In dictionary merging
It is used to unpacks dictionaries and merge them into a single dictionary, where keys from later dictionaries override earlier ones if there's a conflict.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict) # prints: {'a': 1, 'b': 3, 'c': 4}