When you pass keyword arguments to a function, it gets converted to a dictionary. Not the other way around.
Detail explanation of args and kwargs
*args means a function/method can accept any number of positional arguments and will be stored in a list called args.
**kwargs means it can accept any number of named arguments and will be stored in a dictionary called kwargs
Still unclear? Let me give an example (albeit very simple and naive) -
# Suppose you want to write a function that can find the
# sum of all the numbers passed to it.
def sum(a, b):
return a + b
>>> sum(2, 3) # => 5
# Now this function can only find sum of two numbers, what
# if we have 3, 4 or more numbers, how would be go solving that.
# Easy let's take an array/list as an argument -
def sum(numbers):
total = 0
for number in numbers:
total += number
return total
# But now we'd have to call it like -
>>> sum([2, 3]) # => 5
>>> sum(2, 3) # => throws an error.
# That might be ok for some other programming languages, but not
# for Python. So python allows you to pass any number of
# arguments, and it would automatically store them into list
# called args (as a conventions, but it can be called
# anything else say 'numbers')
def sum(*numbers):
total = 0
for number in numbers:
total += number
return total
>>> sum(2, 3, 4) # => 9
# Viola!
Similarly kwargs are used to automatically store all named arguments as a dictionary.