Pass dict with non string keywords to function in

2020-06-16 01:19发布

I work with library that has function with signature f(*args, **kwargs). I need to pass python dict in kwargs argument, but dict contains not strings in keywords

f(**{1: 2, 3: 4})
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: f() keywords must be strings

How can I get around this without editing the function?

2条回答
够拽才男人
2楼-- · 2020-06-16 02:00

I think the best you can do is filter out the non-string arguments in your dict:

kwargs_new = {k:v for k,v in d.items() if isinstance(k,str)}

The reason is because keyword arguments must be strings. Otherwise, what would they unpack to on the other side?

Alternatively, you could convert your non-string keys to strings, but you run the risk of overwriting keys:

kwargs_new = {str(k):v for k,v in d.items()}

-- Consider what would happen if you started with:

d = { '1':1, 1:3 }
查看更多
虎瘦雄心在
3楼-- · 2020-06-16 02:06

Non-string keyword arguments are simply not allowed, so there is no general solution to this problem. Your specific example can be fixed by converting the keys of your dict to strings:

>>> kwargs = {1: 2, 3: 4}
>>> f(**{str(k): v for k, v in kwargs.items()})
查看更多
登录 后发表回答