0

I have created a function

>>> fun(a,b,c):
  print(a,b,c)

Which I can pass a list to, say [1,2,3] by unpacking and we have

>>> fun(*[1,2,3])

1, 2, 3

or I can pass a dictionary d = {1:'a',2:'b',3:'c'}

>>> fun(*d)
1, 2, 3

However, I experience a problem when I attempt to unpack the keyword arguments

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: fun() keywords must be strings

and when I reverse the values and the keys d = {'a':1,'b':2,'c':3}

>>> fun(**d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: fun() got an unexpected keyword argument 'a'

So, two questions: Why does python only allow strings to be keyword arguments (or have I made a mistake)? And why, do I get an unexpected keyword argument when what it's referencing seems clear?

RhythmInk
  • 513
  • 1
  • 4
  • 18
  • 1
    because you defined your function to take 3 keyword arguments and the arguments were `a`, `b`, and `c`. When you unpack the first dict, its equivalent to calling `fun(1=a, 2=b, 3=c)` which is invalid syntax because you can't have integers as keywords – pault Jul 19 '19 at 14:29
  • Why am I not able to have integers as keywords? Nevermind, upon further thought it is immediately clear what the problem is. – RhythmInk Jul 19 '19 at 14:29
  • 2
    Defining `d = {1:'a',2:'b',3:'c'}` and doing `fun(*d)` is equivalent to `fun(1,2,3)` similarly defining `d = {'a':1,'b':2,'c':3}` and doing `fun(**d)` is equivalent to `fun(a=1, b=2, c=3)` So `d = {1:'a',2:'b',3:'c'}` and `fun(**d)` is equivalent to `fun(1=a, 2=b, 3=c)` which cannot be valid – Devesh Kumar Singh Jul 19 '19 at 14:33
  • Defining ```d = {'a':1,'b':2,'c':3}``` then should yield ```fun(**d)``` as equivalent to ```fun(a=1,b=2,c=3)``` so why do I get an unexpected keyword arugment 'a' TypeError? – RhythmInk Jul 19 '19 at 14:36
  • Check the new dupe I added, – Devesh Kumar Singh Jul 19 '19 at 14:37

0 Answers0