Why am I getting this unexpected keyword argument TypeError?

David Dong picture David Dong · Aug 15, 2019 · Viewed 27k times · Source

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?

Answer

Novice picture Novice · Aug 15, 2019

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