Register to get access to free programming courses with interactive exercises

More about named arguments Python: Functions

We can retrieve positional and named arguments in any number of *args.

Getting named arguments as dictionaries

Only named arguments can be obtained as a dictionary, which allows you to store the names in keys:

def g(**kwargs):
    return kwargs

g(x=1, y=2, z=None)
# {'x': 1, 'y': 2, 'z': None}

We can refer to an argument that receives this dictionary as kwargs (keyword arguments).

We write the keyword arguments after all the usual positional ones:

  • *args before the first argument with the default value
  • **kwargs after the last argument with the default value

Let us define a function that takes all kinds of arguments:

def f(x, y, *args, kx=None, ky=42, **kwargs):
    return (x, y, args, kx, ky, kwargs)

f(1, 2, 3, 4, kx='a', ky='b', kz='c')
# (1, 2, (3, 4), 'a', 'b', {'kz': 'c'})

Do not worry. It is rare for a function to use all of these features in real-life code. Nevertheless, it is essential to understand how each type of argument declaration works and how to combine them.

Passing named arguments using dictionaries

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing:">Bookmate</span>
<span class="translation_missing" title="translation missing:">Healthsamurai</span>
<span class="translation_missing" title="translation missing:">Dualboot</span>
<span class="translation_missing" title="translation missing:">Abbyy</span>
Suggested learning programs
Developing web applications with Django
10 months
from scratch
under development
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.