1

Try to pass the dictionary into the function to print them out, but it throws error: most_courses() takes 0 positional arguments but 1 was given

def most_courses(**diction):
    for key, value in diction.items():
        print("{} {}".format(key,value))

most_courses({'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],'Kenneth Love': ['Python Basics', 'Python Collections']})

I have used **kwargs but why cant python unpack the dictionary?

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
Sky Nam
  • 11
  • 1
  • 1
    you don't need the `**` - you are passing a dict as a parameter.. you need the `**` if you would run the method like `most_courses(k1=v1,k2=v2,...)` – DanielM May 19 '19 at 09:30

3 Answers3

2

arguments denoted with a ** in the definition of a function need to be passed with a keyword:

example:

def test(**diction):
    print(diction)

Argument passed without keyword:

test(8)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-5092d794a50d> in <module>
      2     print(diction)
      3 
----> 4 test(8)
      5 test(test_arg=9)

TypeError: test() takes 0 positional arguments but 1 was given

With arbitrary keyword:

test(test_arg=8)

output:

{'test_arg': 8}

edit:

helpful links:

Use of *args and **kwargs

What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

warped
  • 8,947
  • 3
  • 22
  • 49
2

When you pass your dict as a param, you can either do it as you wrote:

most_courses({'Andrew Chalkley':  ... 

in this case most_cources should accept a "positional" param. That's why it raises: most_courses() takes 0 positional arguments but 1 was given.

You gave it 1 positional param, while most_cources (which looks like: most_courses(**d)) isn't expecting any..

You should either do:

most_courses(**{'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],'Kenneth Love': ['Python Basics', 'Python Collections']})

OR change the signiture of your method:

def most_courses(diction):
    for key, value in diction.items():
        print("{} {}".format(key,value))
Aaron_ab
  • 3,450
  • 3
  • 28
  • 42
1

There is no reason to use ** here. You want to pass a dict and have it processed as a dict. Just use a standard argument.

def most_courses(diction):
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895