-1

I got a strange TypeError from the following code snippet. Could you guys help understand what's going wrong here? Thanks.

xs = {'x': 1, 'y': 2, 'z': 0}
ys = {'a': 3, 'b': 4, 'c': 5}
def print_vector(x, y, z):
    print(f'<{x}, {y}, {z}>')

print_vector(**xs) # <1, 2, 0>
print_vector(**ys) # TypeError: print_vector() got an unexpected keyword argument 'a'
Kevin Li
  • 11
  • 2
  • 1
    An image is really not a nice format for this sort of thing, we can't copy and paste for it. Just put the code in your question. – RemcoGerlich Jul 20 '18 at 09:22
  • 1
    On the other hand, the problem is just that your second dictionary has keys a/b/c instead of x/y/z. That's probably a simple typo. So the question should be closed, unless that part is what you meant and you thought it would work (how?). – RemcoGerlich Jul 20 '18 at 09:23
  • https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters – pask Jul 20 '18 at 09:26

1 Answers1

0

Your function print_vector() expects arguments named x, y and z. Your dictionary ys doesn't contain these keys. One solution is to make the function more generic:

xs = {'x': 1, 'y': 2, 'z': 0}
ys = {'a': 3, 'b': 4, 'c': 5}

def print_vector(**kwargs):
    print('<{}, {}, {}>'.format(*kwargs.values()))

print_vector(**xs)
print_vector(**ys)

Prints:

<1, 2, 0>
<3, 4, 5>
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91