Most pythonic way of assigning keyword arguments using a variable as keyword?

只愿长相守 提交于 2019-11-27 09:05:44

Use keyword argument unpacking:

>>> kw = {'a': True}

>>> f(**kw)
<<< 'a was True'

In many circumstances you can just use

f(kw)

as keyword arguments don't have to be specified as keywords, if you specify all arguments before them.

Python 3 has a syntax for keyword only arguments, but that's not what they are by default.

Or, building on @zeekay's answer,

kw = 'a'
f(**{kw: True})

if you don't want to store kw as a dict, for example if you're also using it as a key in a dictionary lookup elsewhere.

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