8

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?

Jwok
  • 646
  • 9
  • 23

4 Answers4

13

call kw function with kw(**table)

Python 3 Doc: link

richard_ma
  • 156
  • 1
  • 6
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):
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • 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 04 '21 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

mb_atx
  • 309
  • 3
  • 2
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)