【问题标题】:Converting Python dict to kwargs?将 Python dict 转换为 kwargs?
【发布时间】:2011-08-08 07:10:02
【问题描述】:

我想使用类继承为 sunburnt(solr 接口)构建一个查询,因此将键值对添加在一起。 sunburnt 接口采用关键字参数。如何将字典 ({'type':'Event'}) 转换为关键字参数 (type='Event')

【问题讨论】:

    标签: python dictionary keyword-argument


    【解决方案1】:

    使用double-star(又名double-splat?)运算符:

    func(**{'type':'Event'})
    

    等价于

    func(type='Event')
    

    【讨论】:

    • 如果你已经有一个名为“myDict”的字典对象,你只需func(**myDict)。即myDict = {"type": "event"}
    • 这在 python 标准文档中有很好的介绍。另请参阅:stackoverflow.com/questions/1137161。 (dmid://juice_cobra_hush)
    • 这非常有用,尤其是在使用将字典转换为 Swagger 模型实例时。谢谢。
    【解决方案2】:

    ** 运算符在这里会有所帮助。

    ** 运算符将解压 dict 元素,因此 **{'type':'Event'} 将被视为 type='Event'

    func(**{'type':'Event'})func(type='Event') 相同,即 dict 元素将转换为 keyword arguments

    仅供参考

    * 将解包列表元素,它们将被视为positional arguments

    func(*['one', 'two'])func('one', 'two') 相同

    【讨论】:

      【解决方案3】:

      这是一个完整的示例,展示了如何使用 ** 运算符将字典中的值作为关键字参数传递。

      >>> def f(x=2):
      ...     print(x)
      ... 
      >>> new_x = {'x': 4}
      >>> f()        #    default value x=2
      2
      >>> f(x=3)     #   explicit value x=3
      3
      >>> f(**new_x) # dictionary value x=4 
      4
      

      【讨论】:

        猜你喜欢
        • 2010-10-24
        • 2019-10-08
        • 2013-06-15
        • 1970-01-01
        • 1970-01-01
        • 2020-10-23
        • 2018-11-15
        • 2012-10-15
        相关资源
        最近更新 更多