I'm testing some code with *args
and **kwargs
, and I wrote a dictionary
for the **kwargs
. For some reason, I'm getting
def func(*args, **kwargs):
if args:
second_test(*args)
elif kwargs:
second_test(**kwargs)
def second_test(stringa, integera, floata):
print("Name: %s, Problems Correct: %d, Points: %f" % (stringa, integera, floata))
profile_1 = ["David", 21, 132.00]
func(*profile_1)
profile_1a = {'Name': 'David', 'Problems Correct': 21, 'Points': 132.00}
func(**profile_1a)
The code starts from line 44
and ends at line 57
. This is the error I'm getting:
TypeError: second_test() got an unexpected keyword argument 'Name'
I've googled "unexpected keyword argument", but I can never find a definition; only other stackoverflow articles. What is wrong with my code?
When passing kwargs
into a function, it expects to find the exact variable name in the list. If instead your dictionary keys were stringa
, integera
, and floata
the function would work without problem.
So you either need to change your function variable names or change the key names in your dictionary to get this to work
keyword argument is all of the "unknown/unexpected" named argument that being passed by name.
for example, let's define a function with one argument
def func(a):
print(a)
now, if we call this function with an "unexpected" named argument like so
func(b=3) # remember we didn't define b as an argument
then we will get a TypeError. However, if we modify the function to accept these "unexpected" named arguments, then we can run the previous code
def func(a, **kwargs):
print(a)
print(kwargs["b"]) # now, if we pass an argument 'b' to the function, this will print its value (if we don't, we get a KeyError)
> func(3, b=15)
3
15
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With