Pass dict with non string keywords to function in kwargs

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

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?

回答1:

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()}) 


回答2:

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 } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!