It's not an issue in your function because you are iterating over the passed dictionary explicitly but, for general cases, *
is used for unpacking args
and **
is used for unpacking kwargs
/ keyword arguments.
This can be seen by the results below -
- Unpacking keyword arguments with ** maps each key to the respective keyword argument. This returns the values for corresponding params as defined in the function.
def func(brand, model, year):
return brand, model, year
dict1 = {"brand": "Ford", "model": "Mustang", "year": 1964}
print(func(**dict1))
#OUTPUT: ('Ford', 'Mustang', 1964)
- A single * unpacks the dictionary to its keys only. Therefore, when these are passed, the function returns the keys as strings. In this case, a proper data structure for passing params would be a list or tuple.
dict1 = {"brand": "Ford", "model": "Mustang", "year": 1964}
print(func(*dict1))
#OUTPUT: ('brand', 'model', 'year')
- Without unpacking, this scenario fails because model is expecting 3 parameters, but got only 1 (dictionary).
dict1 = {"brand": "Ford", "model": "Mustang", "year": 1964}
print(func(dict1))
#OUTPUT:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-731-f73ee817438f> in <module>
1 dict1 = {"brand": "Ford", "model": "Mustang", "year": 1964}
----> 2 print(func(dict1))
TypeError: func() missing 2 required positional arguments: 'model' and 'year'