Here’s another article in the Functions in Python series. This time we’ll be talking about keyword parameters again.
If you haven’t read the previous parts yet, feel free to do so. Here they are:
6) Mutable Optional Parameters
8) Arbitrary Number of Positional Parameters
In the previous article we learned how to pass an arbitrary number of positional parameters to a function. In this article we’ll learn how to pass an arbitrary number of keyword parameters to a function.
We can pass an arbitrary number of keyword parameters to a function using a double asterisk ** like in the following example:
def capitals(**countries):
print(countries)
capitals(France = "Paris", Italy = "Rome", Canada = "Ottawa")
Here’s the output:
{'France': 'Paris', 'Italy': 'Rome', 'Canada': 'Ottawa'}
Unpacking a Dictionary
We could also use this function with a dictionary. A double asterisk would be used to unpack it:
def capitals(**countries):
print(countries)
cap_dict = {"France" : "Paris", "Italy" : "Rome", "Canada" : "Ottawa"}
capitals(**cap_dict)
And the output is:
{'France': 'Paris', 'Italy': 'Rome', 'Canada': 'Ottawa'}
We can use the ** notation also to pass arguments explicitly. The keyword arguments passed this way are used as the keys and values of a dictionary:
def capitals(greeting, **countries):
print(greeting)
for country in countries:
print(f"The capital of {country} is {countries[country]}.")
capitals("Hi, here are the capitals:", France = "Paris", Italy = "Rome", Canada = "Ottawa")
And the output is:
Hi, here are the capitals:
The capital of France is Paris.
The capital of Italy is Rome.
The capital of Canada is Ottawa.