Skip to content
Home » Functions in Python – Arbitrary Number of Keyword Parameters

Functions in Python – Arbitrary Number of Keyword Parameters

Spread the love

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:

1) Introduction to Functions

2) Functions with Parameters

3) The return Statement

4) Mandatory Parameters

5) Optional Parameters

6) Mutable Optional Parameters

7) Keyword Arguments

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'}

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

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.

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply