Passing a list of kwargs?

后端 未结 4 1332
陌清茗
陌清茗 2020-12-04 15:20

Can I pass a list of kwargs to a method for brevity? This is what i\'m attempting to do:

def method(**kwargs):
    #do something

keywords = (keyword1 = \'fo         


        
4条回答
  •  离开以前
    2020-12-04 15:25

    As others have pointed out, you can do what you want by passing a dict. There are various ways to construct a dict. One that preserves the keyword=value style you attempted is to use the dict built-in:

    keywords = dict(keyword1 = 'foo', keyword2 = 'bar')
    

    Note the versatility of dict; all of these produce the same result:

    >>> kw1 = dict(keyword1 = 'foo', keyword2 = 'bar')
    >>> kw2 = dict({'keyword1':'foo', 'keyword2':'bar'})
    >>> kw3 = dict([['keyword1', 'foo'], ['keyword2', 'bar']])
    >>> kw4 = dict(zip(('keyword1', 'keyword2'), ('foo', 'bar')))
    >>> assert kw1 == kw2 == kw3 == kw4
    >>> 
    

提交回复
热议问题