7

I'm trying to get my head around **kwargs in python 3 and am running into a strange error. Based on this post on the matter, I tried to create my own version to confirm it worked for me.

table = {'Person A':'Age A','Person B':'Age B','Person C':'Age C'}

def kw(**kwargs):
    for i,j in kwargs.items():
        print(i,'is ',j)

kw(table)

The strange thing is that I keep getting back TypeError: kw() takes 0 positional arguments but 1 was given. I have no idea why and can see no appreciable difference between my code and the code in the example at the provided link.

Can someone help me determine what is causing this error?

4 Answers 4

13

call kw function with kw(**table)

Python 3 Doc: link

3
  • When I tried this I got TypeError: kw() got an unexpected keyword argument 'Bob'
    – Jwok
    Jul 18, 2018 at 16:46
  • Correction - when I added kw(**table) and def kw(**kwargs) it worked as expected. Thanks @richard_ma !
    – Jwok
    Jul 18, 2018 at 16:50
  • @Jwok If table is a list, you can call kw function with kw(*table) in Python3
    – richard_ma
    Jul 19, 2018 at 5:18
2

There's no need to make kwargs a variable keyword argument here. By specifying kwargs with ** you are defining the function with a variable number of keyword arguments but no positional argument, hence the error you're seeing.

Instead, simply define your kw function with:

def kw(kwargs):
1
  • I don't think this is working. Python believes only one argument is being passed. Just try calling this function with kw(1, 'foo', 'bar) and you get an error
    – Olivierwa
    Feb 4, 2021 at 13:58
0

Writing a separate answer because I do not have enough reputation to comment.

There is another error in the original post, this time in the function definition

Once you have "opened" a dict with the ** operator in arguments, the dict does not exist any more inside the function. So in the function:

def kw(**kwargs):
    for i,j in kwargs.items():
        print(i,'is ',j) 

the local variables will be Bob, Franny and Ribbit, with their respective values

0

table = {'Bob':'Old','Franny':'Less Old, Still a little old though','Ribbit':'Only slightly old'}

def kw(**kwargs): for i,j in kwargs.items(): print(i,'is ',j)

"""Put the ** before the tablet, like this:"""

kw(**table)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.