Abd
Abd

Reputation: 119

Program shows TypeError while passing a dictionary into a function argument

def f(**kwargs):
   print(kwargs)

d = {'0': 'a', '1': 'b', '2': 'c', '3': 'd'}   
f(**d)   # {'0': 'a', '1': 'b', '2': 'c', '3': 'd'}

d = {0: 'a', 1: 'b', 2: 'c', 3: 'd'}   
f(**d)   # TypeError: f() keywords must be strings

Here,I am getting the TypeError while changing the dictionary key value to int type. May i know, why i am getting this error?

Upvotes: 1

Views: 45

Answers (1)

caverac
caverac

Reputation: 1637

The problem in the second case is that you're doing the equivalent of

f(0 = 'a', 1 = 'b', 2 = 'c', 3 = 'd')

which does not make much sense since (as reported in the error) variables identifiers cannot be named using only numbers. A function expects a correct variable identifier but you are using numbers and thus raises an error.

Upvotes: 5

Related Questions